- Introduction to Mockito
Mockito is a java counterfeiting framework. The so-called counterfeiting is to create a "virtual" java class to simulate the behavior of a java class. Phishing may be used for several reasons:
- A class has entered unit testing, but the collaborative class has not been developed;
- Collaboration classes may be flawed, use a counterfeit mechanism to isolate flaws;
- Mock objects that are difficult to obtain during the unit testing phase, these objects are often related to the environment and container, such as: HttpServletRequest
Three events of Mockito, mock counterfeiting, verification and stubbing. The so-called verification is to assert the expected behavior, and the so-called piling is the entry and return of the mock object in a specific situation
2. Maven configuration
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-all</artifactId> <version>1.9.0</version> <scope>test</scope> </dependency> <dependency> <groupId>org.kubek2k</groupId> <artifactId>springockito</artifactId> <version>1.0.9</version> <scope>test</scope> </dependency> <dependency> <groupId>org.kubek2k</groupId> <artifactId>springockito-annotations</artifactId> <version>1.0.9</version> <scope>test</scope> </dependency>
3. Use
// referenced static resource import static org.mockito.Mockito.*; import static org.junit.Assert.*;
1. Simple example to demonstrate verification and piling
@Test public void test(){ //create a mock class Map<String, Object> map = mock( Map.class ); map.put( "key", "value" ); map.clear(); // Verify that the mock class is called verify( map ).put( "key", "value" );// only equals matching //Verify that clear has been called at least once verify( map, atLeast( 1 ) ).clear(); //Pile driving, the parameter that has not been piling returns null Assert.assertEquals( null, map.get( "any" ) ); // after piling when( map.get( "Hello" ) ).thenReturn( "World" ); Assert.assertEquals( "World", map.get( "Hello" ) ); }
From the above example, we can see that we can monitor every call of the mock, and the corresponding mock can accurately simulate the behavior of the object, ignoring the implementation details of the object behavior.
The return value of the object when the mock is not stubbed
- The method that returns Object, mock returns null by default;
- The method that returns the collection, mock returns empty by default;
- The method that returns a number, mock returns 0 by default;
- The method that returns boolean, mock returns false by default;
The mock can be piled multiple times, and each piling will overwrite the previous value
parameter matching
@Test public void test(){ List list = mock( List.class ); //any integer parameter when( list.get( anyInt() ) ).thenReturn( null ); //two arbitrary parameters when( list.addAll(anyInt(), anyCollection() ) ).thenReturn( false ); }In addition to supporting arbitrary integers and people and sets, mock also uses anyBoolean(), anyByte(), anyLong(), etc.
parameter capture
@Test public void test(){ List list = mock( List.class ); ArgumentCaptor<Integer> argument = ArgumentCaptor.forClass( Integer.class ); list.add( 1 );//This parameter will be captured verify( list ).add( argument.capture() ); // perform capture //Further verification of parameters later Assert.assertEquals( new Integer( 1 ), argument.getValue() ); }
return value setting
@Test public void test(){ List list = mock( List.class ); when( list.get( 0 ) ).thenReturn( 10 ); // Set multiple return values, the return value is different every time you call when( list.get( 0 ) ).thenReturn( 1, 2, 3 ); // set exception return when( list.get( 0 ) ).thenThrow( new RuntimeException() ); // Determine the return value based on the input parameters when( list.get( anyInt() ) ).then( new Answer<Object>() { public Object answer( InvocationOnMock invocation ) throws Throwable { return "El-" + invocation.getArguments()[0]; } } ); //Continuous counterfeiting when( list.get( 0 ) ) .thenReturn( 1 ) //The return value of the first call .thenReturn( 2 )//The return value of the second call .thenThrow( new RuntimeException() ); //The return value of subsequent calls //Set the default return value of the unpiled method mock( List.class, new Answer<Object>() { @Override public Object answer( InvocationOnMock invocation ) throws Throwable { return null; } } ); }
number of verification calls
List list = mock( List.class ); // Verify the number of times a call based on an exact argument occurs verify( list, times( 1 ) ).add( 1 ); //once verify( list, times( 2 ) ).add( 2 ); //Secondary verify( list, atLeastOnce() ).add( 1 ); //at least once verify( list, atLeast( 3 ) ).add( 3 ); //at least three times verify( list, atMost( 3 ) ).add( 3 ); //up to three times //Parameter matching also applies when validating: verify( list, atMost( 3 ) ).add( argThat( new ArgumentMatcher<Object>() { public boolean matches( Object argument ) { return false; } } ) ); //Assert that no unverified calls have occurred on the Mock verifyNoMoreInteractions( list );
call true method
List<Integer> list = new ArrayList<Integer>(); List<Integer> spy = spy( list ); // Pile the real object when( spy.size() ).thenReturn( 100 ); //Another piling method to prevent exceptions doReturn( 1 ).when( spy ).get( 0 ); //The following method is not acceptable, because the real method will be called before piling, resulting in IndexOutOfBoundsException when( spy.get( 0 ) ).thenReturn( 1 ); spy.add(1);//Call the real method spy.size();//Call the fake method verify( spy ).add( 1 ); //verify called once
Start Support Annotation
//If you want to enable annotation support, you can use this runtime class //Or manually call MockitoAnnotations.initMocks(this) @RunWith ( MockitoJUnitRunner.class ) public class MockitoTest { //Automatically create Mock @Mock private List<Object> list; }
other
List mock = mock(List.class); when(mock.size()).thenReturn(10); reset(mock); // reset the mock //Mock completed by single line call Car boringStubbedCar = when(mock(Car.class).shiftGear()).thenThrow(EngineNotStarted.class).getMock();