Saturday, September 19, 2015

Android TDD Series: Test-Driving Views Part 2 - Fragments

Well, it's been more than two months since my last post in the series and I've really fallen off of this horse. The good news is that time away from the Android TDD series was well spent. I have just published my first Android app! Now it's time to get back on and get back to some Android TDD!

We started talking about testing views in Android, specifically how to test activities. While activities are certainly a core component, we actually want to minimize how much code we put in them. This is especially true for all view-related code, such as widget-population and listener functionality. Instead, a majority of this functionality should be placed in fragments. Fragments were introduced into the Android framework when it became apparent that activities would be become bloated and difficult the maintain, with a mishmash of life-cycle management, data population, and widget management. By moving all widget-based functionality (including listeners) we are able to more cleanly delineate the responsibilities for each class. Activities should focus on their life-cycle events and populating the view-model which will be used by the fragment, which will be responsible for managing the widgets and their listeners.

To Test Fragments...


You actually need activities.  This is unfortunate because when we unit test we strive to test classes in isolation as much as possible.  That being said it isn't too onerous to unit test fragments; we simply need an activity when we start the fragment.

For now, let's take a look at how to start a fragment test (src/test/java/com/jameskbride/TextFragmentTest.java):


package com.jameskbride;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.widget.TextView;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricGradleTestRunner;
import org.robolectric.annotation.Config;
import org.robolectric.util.ActivityController;

import static org.junit.Assert.assertEquals;

@RunWith(RobolectricGradleTestRunner.class)
@Config(constants = BuildConfig.class)
public class TextFragmentTest {

    private ActivityController activityController;
    private MainActivity activity;

    @Before
    public void setUp() {
        activityController = Robolectric.buildActivity(MainActivity.class);
        activity = activityController.create().start().visible().get();
    }

    @After
    public void tearDown() {
        activityController.pause().stop().destroy();
    }

    public void startFragment(FragmentActivity parentActivity, Fragment fragment) {
        FragmentManager fragmentManager = parentActivity.getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.add(fragment, null);
        fragmentTransaction.commit();
    }

    @Test
    public void whenTheFragmentViewIsCreatedThenTheViewShouldBePopulated() {
        TextFragment textFragment = TextFragment.newInstance();
        startFragment(activity, textFragment);

        TextView myTextView = (TextView)textFragment.getView().findViewById(R.id.my_text_view);
        assertEquals("Hello world!", myTextView.getText());
    }
}

This code is obviously simplified from what you would normally see.  The first thing we do is in the setUp() method, which is to build an Activity and get it into the correct life-cycle event (see my previous post).  Once we are into the actual test itself we have another required step: starting the Fragment.  We accomplish this by getting ahold of the FragmentManager (in this case we're using the SupportFragmentManager, which is actually recommended).  Once we have the FragmentManager we start a new FragmentTransaction and commit that transaction.

Now we have performed enough setup to perform the actual test.  In this case we are simply checking that the text in a TextView widget has been set when the Fragment is created. After we add enough code to get it to compile (create the TextFragment, add the factory method, newInstance(), and create a view which contains an id of "my_text_view" we can run the test via "./gradlew testDebug". This leaves with a failing test which is expecting "Hello world!". Let's get this test passing.

First, our view (src/main/res/layout/text_fragment_layout.xml):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/my_text_view"/>
</LinearLayout>


Next, the Fragment code (src/main/java/com/jameskbride/TextFragment.java):
package com.jameskbride;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class TextFragment extends Fragment{
    public static TextFragment newInstance() {
        return new TextFragment();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.text_fragment_layout, container, false);

        return root;
    }
}


Let's break this down. First, in our newInstance() method we have returned a TextFragment. Second, in the onCreateView method we inflate our view, text_fragment_layout.xml, which contains the TextView with our "Hello world!" string. The test should now pass.  This is just a basic example of how to unit test fragments in Android.

One thing to keep in mind is that just as activities can be tested in their various life-cycle events, so too can fragments.  If we need to to test code in onAttach() method we can simply call it directly.   The technique for testing Fragments is essentially the same as testing activities. 

Hopefully this has been a useful starting point, though one which has been a long while coming!



Saturday, September 12, 2015

Broken Windows and How to Fix Them

It's your first day on the job at a new client and you're excited and ready to get started.  They've got some cool problems they are trying to solve, the tech stack sounds interesting, and you've got work lined up for your team.  You get there and immediately notice that the build board is red.  Not just a little red, but bleeding red.  "Maybe it's just a single bad build" you think to yourself. "I'm sure it will get fixed right away."  

You try not to about it too much while you get settled in and start pulling down the code to build it locally.  It compiles, but there are a number of failing tests.  You notice a number of other details about the code; domain logic is spread throughout, there is bleed-over between the different layers of abstraction, and A LOT of untested code.  Code duplication abounds, and some of the tests are flaky.
You check the build board again, and notice that not only is it still red, but someone has pushed on top with more changes.  When you ask one of the other developers about it they chuckle and reply that it has been red for a while, but it's OK, it's just some of the tests.  No one seems too bothered by this.  You start wondering if you've walked into some parallel universe where a red build is acceptable, or even expected.  How did it get this way? Doesn't this bother anyone? You realize you have your work cut out for you.

Broken Window Theory

So what happened?  How did the state of the project get to this point?  How can a build get into a red state and stay that way?  Unfortunately it is entirely too easy for this to happen.  It only takes one bad changeset and zero developers who care about fixing it.  This happens in software development with maddening frequency, and is an example of the Broken Window Theory.

Broken Window Theory goes like this:

Given a building with one or more broken windows which are not quickly repaired, the tendency is for more windows to be broken and for other acts of vandalism to occur.  People notice that no one cares about the building, and there is no social pressure to prevent the vandalism.  The building quickly falls into disrepair and stays that way.

In software development lots of little changes can contribute to creating an environment which tolerates a continually broken build.  The addition of code which is difficult to test leads to fewer tests. Flaky tests can degrade confidence in the build ("Oh yeah, that build is red because of known flaky test, go ahead and push anyway!"). Just plain broken functionality is allowed to be pushed, and a general lack of design and maintenance can cause the codebase to be become chaotic and difficult to work with.  Maybe there are developers on the team who simply don't know how to write tests, or how to refactor properly.

All of this together can make it disheartening to try to do the right thing, it becomes easy to fall into the trap of "Well, this is just how the codebase is, we should just learn how to live with it." Obviously this is not the answer.

Fixing Broken Windows

So the windows have been broken and the build is red.  How do you fix the situation?  How do you get the build back to a green state and keep it that way?  The answer is simple, if not easy: get the team to care about the build.  Obviously this is easier said than done in many cases.  Often the team has been beaten down by the long-standing degradation of the build, so simply shouting about the problems in the codebase won't solve anything.  Concrete steps must be taken.

Stop Further Damage

To begin with, cordon off the building, draw a line in the sand, stop the bleeding (pick your metaphor here, there are a lot of them), but whatever you do stop the code from getting any worse than it already is.

Take your lead from this guy.

Be prepared to put the breaks on and play the bad guy, because you're about the rock the boat and upset a lot of people who have become comfortable with The Way Things Are.

Your first order of business should be to get the build back to green as quickly as possible.  If that means no one pushes code until that happens then so be it.  Implement an Evergreen Policy which states that if a build goes red it is either fixed immediately, or the changeset is backed out.

The build is an indication of the health of the project, and ultimately it should tell you whether you are ready to deliver or not, so it should become a priority to get it green and keep it green.  The code should compile and all tests should pass every single time.

Make "Done" Include a Healthy Build

For a given unit of work (user story, task, whatever you want to call it) there should be a Definition of Done.  This definition should describe the requirements to be met before that unit of work can be considered complete, and the next unit of work is begun.  Whatever those requirements currently are, they should be updated to include a clean bill of health for the build.  Appropriate tests should be added and the entire build should complete successfully.  Nobody gets to pick up another piece of work until this happens.  Refuse to allow breaking changes into the build.

Increase Confidence

By now you've hopefully gotten the build green, and laid out a plan to keep it green.  Even so, there may be tests which you can't always trust.  These tests might flap occasionally, leaving developers unsure if they've broken something or not.  If you can't trust the build you can't be sure of the quality of the software you're building.  Investigate the root cause of the flapping tests and address it as quickly as possible.  In the meantime take steps to fix the tests themselves as well.  Maybe they need to be rewritten, or moved into another, more stable layer.  Maybe there are timing issues which can solved by increasing the timeout values.  Maybe they should just be eliminated, as flapping tests are useless in terms of confidence in the build. Whatever the case, do whatever you have to create a reliable and consistent build.

Spread the Pain

Don't try to take on the world on your own. Instead, enlist everyone else to your cause.


Make everyone responsible for keeping the build green.  Chances are good you're going to need backing from the technical leadership to get everyone in line, as behavior doesn't change overnight and some developers will need an incentive to change.  Maybe this means a rotating responsibility in the beginning, but the goal is to make everyone responsible for the entire codebase, and at the very least responsible for the code they are pushing.

Educate and Train

A major cause of headache-inducing codebases is that many developers simply don't know how to do better than they already are.  They may not know how to properly unit test, or maybe they haven't been introduced to Test-Driven Development before.  Maybe they are simply inexperienced and need to be educated on common engineering practices and principles, such as SOLID, DRY, and the concepts of clean code.  Take this opportunity to help everyone step up their game.  Start holding a regular code club to practice these principles away from the production code.  Start a programming book club and encourage everyone to participate.  Do something to help everyone improve, as this will pay out for everyone, both in the short term and in the long term.

Communicate

It's amazing how often problems can be solved by simply talking about them.  Encourage the team to communicate about the issues they're having, especially when it concerns a broken build.  Often, simply acknowledging that the build is broken is enough to start a conversation about how to fix it.  Also encourage communication even when the build is not broken; make it a point to regularly get together and talk about what could be improved, both within the code and without.  It doesn't have to be an hour long meeting, it could just as easily be 15 minutes or less, which is enough time to get the team thinking about the problem at hand.

Give It Time

Change doesn't happen immediately, but if you keep at it and keep everyone on their toes it will happen sooner or later.  Eventually you'll notice a difference; instead of the build being red and people just shrugging it off you'll start overhearing conversations about how to get it fixed and fast.  Just as people got used to the build being broken all the time they'll become used to the build being green all the time.  They won't tolerate broken windows, and they'll make an effort to fix them as soon as they happen.



Saturday, September 5, 2015

Android Dev and API Keys - Keep It Secret, Keep It Safe

The Problem

You have an external API you must call which requires an API key.  This key must not be checked into source control.  Maybe you have other values which are different depending what environment you're in. Either way, you don't want these hard-coded into your source code.

The Solution

Disclaimer: The following solution was synthesized from a couple of disparate StackOverflow answers which I am now unable to find.

1. Create a properties file in which to store your sensitive security/environment values.  Properties in this file follow the standard format of key=value.  Lines may be commented out by prefixing them with the "#" symbol.  You'll want to create a properties file for each environment you'll be working in (e.g. debug, release, etc).

IMPORTANT: Add each of these files to your .gitignore file (or your version control equivalent).

Example properties file:
key.password=somepassword
#key.alias=somekeyalias This line is commented out
store.file=/home/jim/keystores/mykeystore.store
api.key=myapikey
store.password=mystorepassword

2. Update your build.gradle file pull the values out of your property file for each environment.

In app/build.gradle:
android {
    //Lots of other configuration stuff not shown here.
    buildTypes {
        debug {
            Properties properties = new Properties()
            properties.load(project.rootProject.file('local.properties').newDataInputStream())
            def apiKey = properties.getProperty('api.key')
            resValue "string", "api_key", apiKey
            // other debug config stuff not shown here            
        }
        release {
            Properties properties = new Properties()
            properties.load(project.rootProject.file('release.properties').newDataInputStream())
            def apiKey = properties.getProperty('api.key')
            resValue "string", "api_key", apiKey            
            // other release config stuff not shown here
        }
    }
}

Notice the lines where we are calling 'resValue "string, "api_key", apiKey'? This is essentially telling the build to replace the resource value "api_key" anywhere it is used with the value in the variable apiKey.

3. Add a string value to your res/values/strings.xml file to refer to your value.
In res/values/strings.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>    
    <string name="api_key_string">@string/api_key</string>
    <!-- Other values not shown here -->
</resources>

4. Update your AndroidManifest.xml file to make your values available to the application via meta-data.

In app/src/main/AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.yourpackage">
    <!-- Other configuration not shown here -->
    <application
        android:name=".some.applicationName"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
            <!-- Other configuration not shown here -->
        <meta-data android:name="api-key"
            tools:replace="android:value"
            android:value="@string/api_key_string"></meta-data>
            <!-- Other configuration not shown here -->
    </application>
</manifest>

Notice that on our <meta-data> tag we have defined an android:name attribute with the value "api-key", and we are using tools:replace="android:value".  This allows us to point to the value being held in our strings.xml file, referred to as "@string/api_key_string".

5. Finally, we can now refer to our value in the production code by accessing it via a Bundle.

Production Code:

        //You'll need to get a hold of your ApplicationContext for this step.  
        String apiKey;
        try {
            ApplicationInfo applicationInfo = yourApplicationContext.getPackageManager()
                    .getApplicationInfo(yourApplicationContext.getPackageName(),
                            PackageManager.GET_META_DATA);
            Bundle bundle = applicationInfo.metaData;
            apiKey = bundle.getString("api-key");
            Log.d(TAG, "api key: " + apiKey);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();  //Do something more useful here!
        }

That's it! By having your production code access this value via Bundle you've effectively abstracted away any environment-specific concerns; neither do you need to hard-code values anywhere in your source tree. This allows you to safely develop code which is portable to any environment, and frees you from worrying about someone getting access to your security-sensitive values simply by checking out your code.

Thursday, June 18, 2015

Android TDD Series: Test-Driving Views Part 1 - Activities


In my previous post we walked through the initial project setup necessary for test-driving in Android.  In that post we also wrote our first test to show that Robolectric was configured correctly, and I mentioned that we would go into more detail about what that test was doing we got to testing in activities.

A Deeper Dive into Activities

So, here we are.  Let's revisit that test and go into detail about what it is actually doing.

package com.jameskbride;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricGradleTestRunner;
import org.robolectric.Shadows;
import org.robolectric.annotation.Config;
import org.robolectric.shadows.ShadowActivity;

import static org.junit.Assert.assertEquals;

@RunWith(RobolectricGradleTestRunner.class)
@Config(constants = BuildConfig.class)
public class MainActivityTest {

    private MainActivity activity;

    @Before
    public void setUp() {
        activity = Robolectric.setupActivity(MainActivity.class);
    }

    @Test
    public void whenTheActivityIsCreatedThenTheContentViewShouldBeSet() {
        ShadowActivity shadowActivity = Shadows.shadowOf(activity);
        assertEquals(R.id.main, shadowActivity.getContentView().getId());
    }
}

Lets break this down.

Notice we have a member variable in the test for our MainActivity, activity, and a setUp() method, with this interesting line:

activity = Robolectric.setupActivity(MainActivity.class);

This line is performing some Robolectric magic, but lets take some of the mystique out of it and make it apparent what is happening.  First, if we dig into Robolectric.setupActivity() we discover what we're really doing is the following:

public static <T extends Activity> setupActivity(Class<T> activityClass) {
    return ActivityController.of(shadowsAdapter, activityClass).setup().get();
  }

The ActivityController is getting a handle on our Activity, and calling setup().get(). This is similar to the builder pattern, and get() is simply returning the Activity back to us. Let's take a look at the more interesting ActivityController.setup():

/**
   * Calls the same lifecycle methods on the Activity called by Android the first time the Activity is created.
   *
   * @return Activity controller instance.
   */
  public ActivityController<T> setup() {
    return create().start().postCreate(null).resume().visible();
  }

Now the magic has been revealed. All we are really doing here is walking through the lifecycle methods, in this case create(), start(), and resume() of the Activity to get it into the desired state (Note that "postCreate()" and "visible()" are not lifecycle events, but Robolectric helper methods.).

The example I showed earlier used Robolectric.setUpActivity(), however this does not give you very fine-grained control, as it always sets the activity in the onResume() event. However most of the testing you'll do around activities will be life-cycle based, or related to when Fragments are created, displayed or replaced (more on Fragments in the next installment). As such you'll want to use the ActivityController instead, as it gives you the ability to put your Activity in the correct state for the event that you care about.  Testing in this manner will look something like this:

    
    private ActivityController<Mainactivity> activityController;
    private MainActivity activity;

    @Before
    public void setUp() {
        activityController = Robolectric.buildActivity(MainActivity.class);
        activity = activityController.create().start().postCreate(null).resume().visible().get();
    }

    @After
    public void tearDown() {
        activityController.pause().stop().destroy();
    }

With this level of control you'll be able to use the ActivityController to put the activity in any state you need.  If you have functionality you need to test in Activity.onPause() simply chain calls to the ActivityController and perform a get() at the end:

        
     activityController = Robolectric.buildActivity(MainActivity.class);
     activity = activityController.create().start().postCreate(null).resume().visible().pause().get();

You may have noticed in the tearDown() method above that we are using the ActivityController to walk the activity through additional life-cycle events. This is important, as it insures that any clean-up you may need to do is performed.

Starting Activities and Services


Beyond life-cycle events, two other common task you'll need to perform include starting other activities or services.  Using Robolectic these are trivial to write tests for.  Let's look at starting an activity first.  Here is an example test you might write:

    
    private ActivityController<MainActivity> activityController;
    private MainActivity activity;

    @Before
    public void setUp() {
        activityController = Robolectric.buildActivity(MainActivity.class);
        activity = activityController.create().start().postCreate(null).resume().visible().get();
    }

    @Test
    public void whenTheActionBarButtonIsPressedThenTheSecondActivityIsStarted() {
        ShadowActivity shadowActivity = Shadows.shadowOf(activity);

        shadowActivity.clickMenuItem(R.id.action_button);

        Intent startedIntent = shadowActivity.peekNextStartedActivity();
        assertEquals(SecondActivity.class.getName(), startedIntent.getComponent().getClassName());
    }

In this test we perform a click on an action bar button to fire another activity and use Robolectric to peek at the next started activity. Let's take a look at the production code:
    //Here we are in the MainActivity
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        switch(id) {
            case R.id.action_button:                
                startActivity(new Intent(this, SecondActivity.class));
                break;
            default:
        }

        return super.onOptionsItemSelected(item);
    }

Pretty simple, right? Similarly, we can test that a service has been started from our activity as well:
    @Test
    public void whenTheActionBarButtonIsPressedThenCustomServiceIsStarted() {
        ShadowActivity shadowActivity = Shadows.shadowOf(activity);

        shadowActivity.clickMenuItem(R.id.action_button);

        Intent startedIntent = shadowActivity.peekNextStartedService();
        assertEquals(CustomService.class.getName(), startedIntent.getComponent().getClassName());
    }

Again, we're using this very basic pattern, only this time with a service. Here is the production code:
//Here we are in the MainActivity
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        switch(id) {
            case R.id.action_button:                
                startService(new Intent(this, CustomService.class));
                break;
            default:
        }

        return super.onOptionsItemSelected(item);
    }



This is obviously just a brief introduction into testing activities in Android. As you can see though, most of the activity functionality centers around testing the life-cycle events. Next time I'll go into detail about testing Fragments, and showing their interactions with activities and how to test for that as well.

As usual if you have any questions don't hesitate to ask, and I'm always looking for feedback. Thanks!

Thursday, May 28, 2015

Android TDD Series: The Setup

Previously I spoke about the challenges in following Test-Driven Development in Android.  Armed with the fore-knowledge of what we're getting ourselves into we're now ready to dive into the first serious attempt at test-driving some functionality in.

The App


To make this series a little more light-hearted I'm going to develop an app I'll call the "Business Unit Estimator".  This app will let the user take a picture of someone or someplace and assign how many "Units of Business" can be accomplished by that person or place.  For example, take the gentleman in the meme image below:

Via Quickmeme

This fellow is wearing a tie (+5 units of business right there), as well as a business jacket (+3 units of business), his hair is immaculate (+1 units of business), and he's on a cell phone (+2 units of business, as obviously more work gets done when you're on a phone).  That's a grand total of 11 units of business.  This guy means business!  Silliness aside this will provide an app we can work on to demonstrate TDD in Android.



Pre-Reqs

I'm going to make a number of assumptions before we get going.  First, I'm going to assume you have the following installed on your system:

  • Android Studio 1.1+
  • The latest Android SDK (the previous link will get this for you as well)
  • Java 7 (note: we don't want 8 here, as Android is not compatible with 8)
  • Gradle (preferably installed via GVM)
I'm also going to assume that you know how to create an Android project in Android Studio via the usual File -> New -> New Project with a "Blank Activity".  If you'd like a shortcut on creating the project feel free to check out the demo app on my Github page.

Setup

This entry in the series will focus on your environment setup to allow Test-Driving to occur via unit tests and Robolectric.

Robolectric is an Android unit testing framework that allows you to write tests which will run on the JVM, rather than on the emulator.  This has several benefits.  First, it will greatly shorten your feedback loop, as tests which run on the JVM run extremely fast.  Compare this with the out-of-the-box tools provided by Google which by and large require you to deploy code to emulator, wait for it to load, and finally wait for the test to run and you'll see a huge difference.  A secondary benefit here is that running on the JVM allows you to use a mocking framework such as Mockito to control the behavior of your dependencies.

Throughout this series I'll be using Robolectric 3.  Let's add the dependencies we need in our app/build.gradle file:


dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.1.1'

    testCompile 'org.hamcrest:hamcrest-integration:1.3'
    testCompile 'org.hamcrest:hamcrest-core:1.3'
    testCompile 'org.hamcrest:hamcrest-library:1.3'
    testCompile 'junit:junit:4.12'
    testCompile 'org.mockito:mockito-core:1.+'
    testCompile 'org.robolectric:robolectric:3.0-SNAPSHOT'
    testCompile 'org.robolectric:shadows-support-v4:3.0-SNAPSHOT'
}

This block should pull in everything we need to write unit tests.  While we won't be using Mockito just yet, we'll need it soon enough.  The shadows-support dependency will provide additional support for accessing parts of the Android SDK in the test environment.  We're also going to use the 3.0-SNAPSHOT versions here as Robolectric 3 is still in RC at the moment; fear not, the API solid despite that.

Next we need to add the app/src/test/java folder in our project structure, as it is not added for us when the project is generated:

Adding the app/src/test/java folder.

Our First Test

Once this is completed we can add our first test:


package com.jameskbride;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricGradleTestRunner;
import org.robolectric.Shadows;
import org.robolectric.annotation.Config;
import org.robolectric.shadows.ShadowActivity;

import static org.junit.Assert.assertEquals;

@RunWith(RobolectricGradleTestRunner.class)
@Config(constants = BuildConfig.class)
public class MainActivityTest {

    private MainActivity activity;

    @Before
    public void setUp() {
        activity = Robolectric.setupActivity(MainActivity.class);
    }

    @Test
    public void whenTheActivityIsCreatedThenTheContentViewShouldBeSet() {
        ShadowActivity shadowActivity = Shadows.shadowOf(activity);
        assertEquals(R.id.main, shadowActivity.getContentView().getId());
    }
}

There is a lot going on here which we're going to cover in more depth later on, but for now you need to know that the @RunWith and @Config annotations are required to run the Robolectric test. You should also be aware that there are multiple versions of BuildConfig.class, and you'll need to use the one which is generated for your project and not the android.support.v4 or android.support.v7.appcompat versions. Using these versions will cause errors. I'm going to skip over the setup for the moment (we'll cover this in the next entry in the series) and jump straight to the test. When we generated the project a MainActivity class was generated for us under app/src/main/java.

package com.jameskbride;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;


public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
Unfortunately (from a TDD perspective) it also added some logic to set the content view. Our first test is going to add coverage for this functionality.
    @Test
    public void whenTheActivityIsCreatedThenTheContentViewShouldBeSet() {
        ShadowActivity shadowActivity = Shadows.shadowOf(activity);
        assertEquals(R.id.main, shadowActivity.getContentView().getId());
    }
As you can see we are using a ShadowActivity, and asserting that the content view ID has been set.  Let's execute the test. From the root of our project we'll run:
./gradlew testDebug

This causes a compilation error, as the id for main doesn't exist yet.
/home/jim/projects/BusinessUnitEstimator/app/src/test/java/com/jameskbride/MainActivityTest.java:28: error: cannot find symbol
        assertEquals(R.id.main, shadowActivity.getContentView().getId());
                         ^
  symbol:   variable main
  location: class id
1 error
:app:compileDebugUnitTestJava FAILED
Let's make this test pass by adding the id field which will allow us to verify that it is set as the content view.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"
    android:id="@+id/main">

    <TextView android:text="@string/hello_world" android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</RelativeLayout>

The test is passing now and we've successfully demonstrated how to setup and run a Robolectric test. If you'd like to get hands-on with the example code at this point you can check out out from Github.  Join me next time when we'll go more into depth on test-driving Activities.  Also, I'm always looking for feedback, so please leave comments.  Thank you!

Tuesday, May 19, 2015

Code, Creativity, and Beauty

Earlier today I was teaching a class on scrum and XP practices.  During the course of a conversation on Test-Driven Development I made a statement to the effect of “I want to let my tests drive out my design, and not the other way around”.  One of the individuals in the class protested against this. Not against TDD mind you, but against the idea of simply following the narrow path and narrow design that the test was going to cause.  His position was that this method pays no heed to the “creative nature” of software development.  There was further conversation regarding the nature and implementation of TDD that isn’t pertinent here, but his statement stuck with me.

Is there an inherent creativity to software development?

This thought stayed with me for the rest of the day, and as I was washing the dishes just minutes ago I had a sudden dialog in my head on the subject.  You might say (ironically) that my muse visited me, and I was inspired to do something creative.  I rushed to finish the dishes and feverishly started writing out these thoughts before I lost them.

In my daily practice I do not typically stop to consider if, while test-driving a feature, what I’m doing is creative in nature.  I’m building useful things.  These things are going to be employed by someone for a purpose.  Their nature is that of tools, albeit sophisticated tools which are capable of great feats. I know what the thing should do, and I’m writing test code in a way to force the behavior of the code.  Is that creative?  Obviously the simple act of putting syntax to electrons is creative in the sense that you literally just created form and structure where none were before, just as putting these words together for you to read is a creative act.  The question I’m asking is whether there is anything inherently creative (aside from the act itself) in writing code beyond fulfilling a purpose?

Another thought: Can code be considered “beautiful”?

The individual in question also made a comparison of code to music score which I honestly can’t remember now.  I wish I could, but again, this got me thinking.  From my point of view, music and code come from two very different worlds.  Music is creative and beautiful and simply is.  It has not been written to serve a purpose beyond mere entertainment, while software development in general and code in particular was very specifically created to be utilitarian.

There is certainly code which is written purely to be creative and beautiful.  One need search no further than Perl Poetry for examples.  However, ask the average developer if the code that they are working on is beautiful and see how they respond.  They may surprise me, but I think my chances are more than just good that they would describe what they were doing as creating tools to serve a purpose, and beauty and creativity be damned.

Having said this I certainly don’t believe that the act of creating something is in any way at odds with imbuing it utility and purpose.  As a software developer I’ve seen (and endeavored to create, successfully or not) code which is elegant in its simplicity and utilitarian in its application.

Supposing code can be beautiful, how it its beauty derived?  Is is beautiful because it serves a purpose?  Or can it be beautiful simply in its own right?  Can a shovel be called beautiful?  After all, code and shovels are tools which both serve a purpose, though the shovel is infinitely more simple (elegant?).  There is the old saying that beauty is in the eye of the beholder, and that may be so.  If it is, then all code, regardless of its function (or non-functioning nature as the case may be!), could potentially be called beautiful.  This is a concept that is beyond my normal thought processes.  If a thing created for a purpose fails in its purpose can it still be considered beautiful?  If I can’t use the shovel to move material from one location to another can it, as a tool, still be considered beautiful?

To use a metaphor which is probably more familiar to most software developers, can a brick in a cathedral be considered to be beautiful?  Yes, the brick might be used to build a cathedral, and I believe it is a safe thing to say that most people consider cathedrals to be quite beautiful, but is the brick itself beautiful? To take the metaphor further people often point to cathedrals in awe, stating how incredibly beautiful and inspiring they are.  They point to elegant arches, flying buttresses, and columns, and remark at the feelings they invoke in the onlooker.  In deed, part of the purpose (see what I did there?) of cathedrals is to cause a sense of awe and grandeur in worshippers.  The church and its architects, purposely designed it that way.  They also, by the way, designed the arches, flying buttresses, and columns for specific purposes as well.  All of them in their own way support the system of the cathedral, that is they keep the building from collapsing in on itself.  Can they be considered beautiful?  Certainly, as history and wide opinion shows us. However, at the same time they are far more *useful* in purpose than many people realize.  Were they created to be intentionally beautiful while at the same time serving important purposes, or were they simply created to fulfill a purpose?

As software developers is the act of writing software inherently creative, and is the code inherently beautiful, or is it simply the act of building a tool for a utilitarian purpose?

Thursday, May 14, 2015

Android TDD Series: The Challenges

Six months ago I embarked on a journey to write my first Android app.  I'm still on that journey, and though I haven't released yet (soon!) I've learned a number of hard lessons that I'd like to share with those who are on the same path in the hopes that it will make their own journey a little easier.

Before I get to those lessons though I want to talk about some of the challenges I faced when I first approached Android development. First among them is the fact that...


You're Developing Against A Moving Target

Mobile is hot right now, and Android is constantly being updated to keep pace.  When I first started working on the my app KitKat was the latest and greatest.  Lollipop was released a month later, and at the time of this writing it already has close to 10% of the Android market share.  The build tools and support libraries are also constantly being updated, as well as the Gradle plugin and the most popular Android IDE, Android Studio.  As such, the API and your development environment can shift quickly, and library developers have to scramble to keep up.  Information that was accurate a couple of months ago can now be completely out of date.  Libraries that were compatible last week may suddenly stop working.  It's a fast-paced environment, and if you're going to be an Android developer you should be prepared to keep up.  This means following the latest Android news, keeping an eye on third-party tools, and being ready to update on a moment's notice.

As if hitting a moving target wasn't hard enough....



The Framework Is Not Designed For Maintainability


Android was written by people who were attempting to anticipate the varied needs of future app developers, and it's quite obvious that some needs were prioritized over others.  It's also quite obvious that these people (naturally) brought their own biases and schools of thought into the project.  As such, things like testable, maintainable designs and the application of well-understood principles such as Dependency Injection took a backseat to performance.

Reading the Android documentation on managing your memory usage is like reading a diatribe against every good practice you've ever used.  Thinking of decomposing your code into smaller, more focused, more maintainable classes?  Don't do that, think of the overhead!  Want to pull in a known library that meets your needs?  Heavens no, who knows what that library is doing. You should just write your own!  Google even goes so far as to suggest in their documentation that you shouldn't design apps to use the aspects of the framework they themselves provided.  All of these things we do to make our code easier to maintain and test (much less useful!) are flat-out discouraged in the official docs and maddeningly apparent in the implementation.

Admittedly these are some easy potshots to take at Google's expense, and they certainly bring up some interesting data points in regards to their design recommendations.  However, I'm of the opinion that the state of the art for Android has advanced far beyond the point that these recommendations make any sense any more.  This is true in just about every respect; the hardware has improved in leaps and bounds in the space of just a few short years, the ecosystem around Android has grown tremendously, the tooling has been steadily improving, and a thriving community provides an endless number of useful libraries.

Yes, we should eat our vegetables, brush our teeth, and keep performance in mind, but this in no way means we should simply roll over and forget all of the lessons we learned outside of mobile arena.  Gone are the days in which it was acceptable to write monster methods simply to save a few bytes instead of writing new classes and methods.  Gone are the days in which it was acceptable to new-up every dependency inline and call it good enough.   These days there is simply no excuse to not apply the same level of craftsmanship to Android applications as we would to any other project, which leads me to my next point...


TDD Is Hard (But Not Impossible)

There's no two ways about it, Test-Driven Development in Android is daunting.  Coupling the issues with maintainability I mentioned above with the fact that out of the box there are little to no testing tools available makes getting started with TDD a difficult proposition.  Luckily, the Android community has risen to this challenge, and Google has responded to the need for test support with updates to the build tools and other improvements.  Testing tools such as Robolectric used in conjunction with dependency injection frameworks such as Dagger and a healthy dose of mocks (via Mockito or similar) go a long way towards making testing a much less frustrating experience. Functional testing is now simplified as well, as frameworks such as Espresso and Robotium provide easier and more reliable UI interactions than the standard ActivityInstrumentationTestCase2 style tests.  

Even with these tools though testing is still not easy if you're not careful to design your app to be testable.  It is all too easy to simply succumb to the framework if you don't take the time to become intimately familiar with its ins and outs, and to learn when you can and should ignore a design recommendation.  Inline, anonymous listener classes?  As Dikembe Mutombo would say, "Not in my house!"  Business logic embedded in a framework class?  Nope!  It takes diligence and a critical eye for every design decision if you're going to test-drive your code in Android.  Be ready to go off the beaten path.  By the way....


If the Path Doesn't Exist, You Might Have to Build It

As I said earlier, Android is a moving target, and library developers have to scramble to keep up.  Often the pace of advancement is quick enough that the support you're looking for might simply not be there yet.  I've already had to contribute to more than one project in order to remove roadblocks for development, and chances are good that if you're reading this as an aspiring Android developer you might have to as well.  If you're using Robolectric be ready to extend Shadow classes when it becomes necessary.  Also, don't be afraid of cloning a project and pulling down the source to research a bug in your third party libraries, or of figuring out a fix to contribute back. 


These are just a few of the challenges I've encountered while developing my first Android app, and I've outlined them here to give other developers an idea of what to expect when they enter this arena. Over the course of the next several months I'll be writing an Android TDD Series, in which I'll try to provide concrete examples of how to test-drive various pieces of functionality in an example app.  I hope you'll join me here, and I look forward to your feedback.  Thanks and happy app dev'ing!