Testing in Android : Part 3 : Using Mockito

Testing in Android : Part 3 : Using Mockito
By default , local unit tests are executed against a modified version of android.jar library. This library does not contain any actual code. So, if we make any call to android classes, it will throw an exception. We can use Mocking Framework mockito to mock objects and define outputs of certain method calls.

Mockito is an open sourced testing framework for Java that allows to create mock objects in Automated unit Tests.In this example, we will “mock” “MainActivity” class.

Steps to use Mockito Framework :
  1. include mockito library dependency in your build.gradle :

    testCompile "org.mockito:mockito-core:1.9.5"
  2. Add  @RunWith(MockitoJUnitRunner.class) before unit test class name
  3. To create any mocked object of Android Dependency, use @Mock before that object name

    @Mock
    Context mMockedContext;

    Or you can use static method mock() to mock any class :

    MainActivity activity = Mockito.mock(MainActivity.class);
  4. use when().thenReturn() to use a condition and return value for it.

    @Test
    public void test_when_thenReturn(){
    MainActivity activity = Mockito.mock(MainActivity.class);
    when(activity.getName()).thenReturn("MainActivity");
    assertThat(activity.getName(),is("MainActivity"));
    }
  5. use verify() to detect if any conditioned are met or not like if a method is called with a certain parameter, if it was called once or twice etc

    public void test_verify(){
        MainActivity activity = Mockito.mock(MainActivity.class);
    
        when(activity.getName()).thenReturn("MainActivity");
        when(activity.getNumber(anyInt())).thenReturn(0);
    
        //verify if getName() is never called
        verify(activity,never()).getName();
    
        //now call it one time
        activity.getName();
    
        //verify if it is called once
        verify(activity,atLeastOnce()).getName();
    
        //call getNumber method with a parameter
        activity.getNumber(1);
    
        //verify if getNumber was called with parameter 1
        verify(activity).getNumber(1);
    }

    similarly we can use atLeast(int param),times(int param),atMost(int) etc. with verify

  6. we can use spy() of a real object. It will call the real method of that object.

    public void test_spy(){
    List list = new LinkedList();
    List spyList = spy(list);when(spyList.size()).thenReturn(200);assertThat(spyList.size(),is(200));
    }

That’s it. Clone this project from GitHub and try it by yourself.

No Comments

Post a Comment