Android Unit Testing

This post is going to cover unit testing a native Android application.   While working on my own modest Android application, I wanted to add some non-instrumented unit tests and was surprised  how challenging it was to use mock objects.  Admittedly, instrumented tests running on a emulator or actual device is probably a better way to go, but I wanted a faster way to make sure that my internal logic was still working as expected when making changes.

Code Under Test

Here is one example of some of the code I was trying to test:

public class ViewOnTouchDragStartListener implements View.OnTouchListener {

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
            ClipData clipData = ClipData.newPlainText("", "");
            View.DragShadowBuilder dsb = new View.DragShadowBuilder(view);
            view.startDrag(clipData, dsb, view, 0);
            view.setVisibility(View.INVISIBLE);
            return true;
        } else {
            return false;
        }
    }
}

When I started writing my test method my plan was simple, just use Mockito to create mocks for the View and MotionEvent objects, set the expectations, run the test and watch the green bar. Instead all I received was a slew of RuntimeException(“Stub!”) errors. So I went back to the drawing board (Google) which led me to PowerMock. I have been using Mockito for some time now and I was aware of PowerMock that can be used to extend the capabilities of frameworks like Mockito and EasyMock to enable mocking of constructors, private methods and static methods among others. This seemed to be exactly what I was looking for to help with my Android unit testing issues.

Unit testing take two

I downloaded powermock-mockit-junit-1.4.10 (the most current as of this writing) There are also downloads available that work with TestNG and EasyMock. After some consultation with the documentation here is my improved unit test

@RunWith(PowerMockRunner.class)
@PrepareForTest({MotionEvent.class, ClipData.class,ViewOnTouchDragStartListener.class,View.class})
public class ViewOnTouchDragStartListenerTest {
    private ViewOnTouchDragStartListener dragStartListener;
    private View view;
    private MotionEvent motionEvent;
    private ClipData clipData;
    private View.DragShadowBuilder dragShadowBuilder;

    @Before
    public void setUp() throws Exception {
        dragStartListener = new ViewOnTouchDragStartListener();
        view = PowerMockito.mock(View.class);
        PowerMockito.mockStatic(ClipData.class);
        clipData = PowerMockito.mock(ClipData.class);
        motionEvent = PowerMockito.mock(MotionEvent.class);
        dragShadowBuilder = PowerMockito.mock(View.DragShadowBuilder.class);
    }

    @Test
    public void testOnTouchActionDown() throws Exception {
        PowerMockito.when(motionEvent.getAction()).thenReturn(MotionEvent.ACTION_DOWN);
        when(ClipData.newPlainText("", "")).thenReturn(clipData);
        PowerMockito.whenNew(View.DragShadowBuilder.class).withArguments(view).thenReturn(dragShadowBuilder);
        boolean isActionDown = dragStartListener.onTouch(view, motionEvent);
        InOrder inOrder = inOrder(view);
        inOrder.verify(view).startDrag(Matchers.<ClipData>anyObject(), Matchers.<View.DragShadowBuilder>anyObject(), eq(view),eq(0));
        inOrder.verify(view).setVisibility(View.INVISIBLE);
        assertThat(isActionDown,is(true));
    }

I found this fairly straight forward to implement, and best of all, I started getting green for all of my unit tests! I was impressed with PowerMock’s ability to mock out the constructor call to View.DragShadowBuilder inside the ViewOnTouchDragStartListener’s onTouch method (line 24 of test code sample and line 5 of the sample code, respectively). Admittedly, there probably should have been a separate method that would create and return the DragShadowBuilder object then use the PowerMock/Mockito spy functionality that allows you to selectively mock out methods on real objects.

Hopefully this will help you with your Android unit testing endeavors.

If you found this post helpful subscribe to my feed.    

Comments

  1. Namitha says:

    I want to know how to test intent in android app. In my project I have broadcast receiver it receives some message and passes it to the perticular number. In this how to test message received and how it calls different intents of classes. Can you please send me any sample code

    Thank you

  2. James McMurray says:

    Do you have a working example of the project(s) required to get this running? I’ve tried creating a base project and test project with the two files in it but can’t get it to run. Everything seems to compile ok but it dies with the less-than-helpful error message “Failed to launch test” in the android console. Logcat doesn’t show anything either.

    If I make the test extend AndroidTestCase then it’ll at least install, but linking fails to find some TestNG files and it throws a class not found exception for org.junit.runner.RunWith.

    • Hi James,

      I’m using Intellij version 11.1 and I’m running the test shown in the blog as a plain junit test. I’m pretty sure that this test will not run on the emulator, which I’m assuming you tried from your statement about looking at the android console. I plan to put the whole project on github soon, but I’m in the middle of trying to incorporate Guice into the project, so I’m doing a bit of refactoring and it might take a little while. Hope this helps, let me know if you have any other questions.

      Cheers,
      Bill

  3. To fix your original issue with RuntimeException(“Stub!”) you should check out ‘Robolectric’ its pretty cool, allows you to do Unit Testing with Mockito (no need for power mock)

    • I actually have been planning to try out Roboelectric and write about my experiences with it. Thanks for taking the time to comment.

      Cheers,
      Bill

  4. Thank you for sharing. I struggled with the exact same problems.

Trackbacks

  1. [...] Android Unit Testing This post is going to cover unit testing a native Android application. Source: codingjunkie.net [...]

Speak Your Mind

*