DZone
Java Zone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone > Java Zone > Android Unit Testing

Android Unit Testing

Bill Bejeck user avatar by
Bill Bejeck
·
Oct. 09, 11 · Java Zone · Interview
Like (0)
Save
Tweet
9.18K Views

Join the DZone community and get the full member experience.

Join For Free

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.

 

From http://codingjunkie.net/android-unit-testing/

unit test Android (robot)

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Upsert in SQL: What Is an Upsert, and When Should You Use One?
  • Top 20 Git Commands With Examples
  • Making Your SSR Sites 42x Faster With Redis Cache
  • How to Leverage Method Chaining To Add Smart Message Routing in Java

Comments

Java Partner Resources

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo