How To Set Up Mockito To Mock Class For Android Unit Test
Solution 1:
It is not difficult to set up Mockito in your project. The steps are below.
1. Add the Mockito dependency
Assuming you are using the jcenter repository (the default in Android Studio), add the following line to the dependencies
block of your app's build.gradle file:
testImplementation "org.mockito:mockito-core:2.8.47"
You can update the version number to whatever is the most recent Mockito version is.
It should look something like this:
dependencies {
// ...
testImplementation 'junit:junit:4.12'
testImplementation "org.mockito:mockito-core:2.8.47"
}
2. Import Mockito into your test class
By importing a static class you can make the code more readable (ie, instead of calling Mockito.mock()
, you can just use mock()
).
importstatic org.mockito.Mockito.*;
3. Mock objects in your tests
You need to do three things to mock objects.
- Create a mock of the class using
mock(TheClassName.class)
. - Tell the mocked class what to return for any methods you need to call. You do this using
when
andthenReturn
. - Use the mocked methods in your tests.
Here is an example. A real test would probably use the mocked value as some sort of input for whatever is being tested.
publicclassMyTestClass {
@Test
publicvoidmyTest() throws Exception {
// 1. create mock
Spanned word = mock(SpannedString.class);
// 2. tell the mock how to behavewhen(word.length()).thenReturn(4);
// 3. use the mock
assertEquals(4, word.length());
}
}
Further study
There is a lot more to Mockito. See the following resources to continue your learning.
- Mockito documentation
- Unit tests with Mockito - Tutorial
- Mockito on Android
- Testing made sweet with a Mockito by Jeroen Mols (YouTube)
Or try this...
It is good to learn mocking because it is fast and isolates the code being tested. However, if you are testing some code that uses an Android API, it might be easier to just use an instrumentation test rather than a unit test. See this answer.
Post a Comment for "How To Set Up Mockito To Mock Class For Android Unit Test"