DZone
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
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. Android Unit Testing

Android Unit Testing

Bill Bejeck user avatar by
Bill Bejeck
·
Oct. 09, 11 · Interview
Like (0)
Save
Tweet
Share
9.40K 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

  • Leverage Lambdas for Cleaner Code
  • Effective Jira Test Management
  • gRPC on the Client Side
  • Chaos Data Engineering Manifesto: 5 Laws for Successful Failures

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • 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: