How to use Mockito for unit testing
Mockito is an open source unit testing framework for Java, which can help developers create and manage Mock object during testing.
The core idea of Mockito is to use Mock object instead of real objects to better control the test environment and test results. By using Mock object, we can simulate various behaviors and states required for testing, so as to achieve effective, reliable and efficient testing of the code under test.
The commonly used key methods of Mockito include:
1. mock(Class<T> classToMock)
-Used to create a Mock object of the specified class.
List<String> mockedList = Mockito.mock(List.class);
2. when(mockedObject.methodCall()).thenReturn(result)
-Defines that when a method of a Mock object is called, the specified result is returned.
when(mockedList.get(0)).thenReturn("first");
3. verify(mockedObject, times(num)).methodCall()
-Verify that a method of the Mock object has been called the specified number of times.
verify(mockedList, times(1)).add("one");
4. doThrow(exceptionClass).when(mockedObject).methodCall()
-Defines that the specified exception will be thrown when a method of the Mock object is called.
doThrow(new RuntimeException()).when(mockedList).clear();
5. ArgumentMatchers
-Mockito also provides the ArgumentMatchers class, which is used to flexibly match parameters in method calls of Mock object.
when(mockedList.get(anyInt())).thenReturn("element");
Mockito can be added to a project through the following Maven dependencies:
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>3.9.0</version>
<scope>test</scope>
</dependency>
The above is a brief introduction to Mockito and sample code of commonly used key methods. By using these methods, we can achieve precise and controllable unit testing of the tested code.