Unit test with Mockito

Tram Ho

Preamble

Mockito is a framework that supports creating unit tests using mock objects.

A mock is an object that has properties of the real object while ignoring the hassle of creating a real object.

The reason we should use mock object to perform unit test:

  • No need to initialize as real objects so will not be dependent on real objects in the application

  • Unit tests will be faster

  • The code also looks better

Unit test with Mockito

Suppose we have 1 MovieViewModel as follows:

Now that we need to write the unit test for the getMovies () method, the steps are as follows:

Add Mockito dependence

To add Mockito dependence, we need to add the following line in build.gradle (app)

Create a Mock class to perform unit tests

Create a class named MovieViewModelUnitTest in the test package

(Note there are 2 test directories, "androidTest" and "test", "androidTest" is for us to run the test on the real device and "test" is for us to run the test without the device. Here we create in package "test")

Analyze the object to be tested

Here we need to test the getMovies () method of MovieViewModel, in this method we are using MovieRepository, MutableLiveData so we need to mock these 2 objects to use

Use mock objects to define methods

Above, I gave you a rough guide on how to use Mockito to perform unit tests. Of course there are still many other situations that you have to handle a little more complicated but generally Mockito is quite easy to use because basically still have to pass through the 3 steps above. To find out more, refer here

Share the news now

Source : Viblo