Intro to Android

Lab: Utility Functions

Let's add utility functions to our support package. It'll help reduce the some of the boilerplate when we work through later labs.

Technically with TDD you'd wait until the exact moment you need the code to write it. I prefer practicality over being pedantic.

Create Assert.java

public class Assert
{
    public static void assertViewIsVisible( View view )
    {
        assertNotNull( view );
        assertThat( view.getVisibility(), equalTo( View.VISIBLE ) );
    }
}

Create ResourceLocator.java

public class ResourceLocator
{
    public static String getString( int stringId )
    {
        return Robolectric.application
                          .getString( stringId );
    }

    public static Drawable getDrawable( int drawableId )
    {
        return Robolectric.application
                          .getResources()
                          .getDrawable( drawableId );
    }
}

Create FragmentUtil.java

With the version of Robolectric we're using, we need to make our own version of a fragment starter.

Robolectric has one for support fragments, but doesn't have one for "normal" platform fragments. This should be in an upcoming release. We've copied their framework version here and modified to use normal fragments. You can find the latest source for FragmentTestUtil on github.

public class FragmentUtil
{
    public static void startFragment( Fragment fragment )
    {
        Activity activity = createActivity();

        FragmentManager fragmentManager = activity.getFragmentManager();
        fragmentManager.beginTransaction()
                       .add( fragment, null )
                       .commit();
    }

    private static Activity createActivity()
    {
        return Robolectric.buildActivity( Activity.class )
                          .create()
                          .start()
                          .resume()
                          .get();
    }
}