Unit Testing in android - Part 1

rahul reddy
2 min readOct 3, 2018

--

Writing unit test is an important part of coding. Developers will be more confident in refactoring a code with good number of unit tests that one with out unit tests. Also it will be easy to find bugs in a code with unit tests because we can know exactly which part of the code is breaking. So how to write unit tests for android easily?

In android main problem in writing unit tests is all the android components that are to be mocked. So in order to make writing unit tests simple we generally follow one of the following design patterns:

  1. MVP (Model View Presenter)
  2. MVVP (Model View ViewModel)

In this I will cover MVP model. In MVP:

  1. Model is typically POJO’s that are used by Presenter and View to convey information or to act upon.
  2. View is passive interface that displays data.This is place where we set data & make UI related changes like hiding , moving view.
  3. Presenter decides presentation logic , our business logic resides here. It talks to repository gets data, format it to display in view. It decides what should be displayed on View.

The trick of making writing unit tests easy lies in designing the code such that the basic business logic is separated from the android related components. For this we wrap all the android related components using custom interfaces so that we need to mock only our objects, not the android objects. MVP design pattern helps with this. In MVP we try to isolate business logic as much as possible into presenter. Android related objects are hidden under the interface provided by the view.

This allows us to write normal unit tests for the presenter and Instrumental tests for the android components. In this post I will discuss the unit testing using JUNIT and Java. In the next post I will explain unit testing using kotlin.

Consider presenters like bellow:

public class MyPresenter {    private MyView myView;    public MyPresenter(MyView myView) {
this.myView = myView;
}
public void doSomeThing(int decisionValue) {
if(decisionValue == 1) {
myView.goToFirstScreen();
}
else {
myView.goToDefaultScreen();
}
}
}

for this type of presenters we need to mock the view. In this I will use Mockito.

To mock a function call we use verify. See the below example.

@Test
public void doSomeThingGoToFirstScreenTest()
{
MyView loginView= mock(MyView.class);
MyPresenter loginPresenter = new MyPresenter(loginView);
myPresenter.doSomeThing(1);
verify(myView).goToFirstScreen();
}

@Test
public void doSomeThingGoToDefaultScreenTest()
{
MyView loginView= mock(MyView.class);
MyPresenter loginPresenter = new MyPresenter(loginView);
myPresenter.doSomeThing(0);
verify(myView).goToDefaultScreen();
}

--

--