In the test process, will inevitably encounter the interaction of the peripheral system does not give the force of the situation, when the mock will come in handy, the previous time with the classmate chat to this piece, he recommended to me mockito this mock tool, try it, really good, here to introduce the following this tool:
1, the characteristics of Mockito
- It can mock the interface and mock the entity class (which we can do with the test Framework Mock tool)
- simple annotation syntax [email protected]
- Easy to understand, simple in grammar
- Support Sequential validation
- Customized parameter matching device
2, the Mockito configuration
Just rely on the jar package:
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<scope>test</scope>
<version>1.8.5</version>
</dependency>
2, the use of Mockito
How to Annotate:
Just add the @mock to the object you want to mock, such as:
public class ArticleManagerTest {
@Mock private ArticleCalculator calculator;
@Mock private ArticleDatabase database;
@Mock private UserProvider userProvider;
Private Articlemanager Manager;
Do not use annotations:
The entity class to mock linkedlist mockedlist = mock (linkedlist.class);
The return value of the impersonation method call
Mockito.when (mockedlist.get (0)). Toreturn ("first");
Mockito.when (Mockedlist.get (1)). Tothrow (New RuntimeException ());
Print out "First"
System.out.println (mockedlist.get (0));
Throws Exception System.out.println (Mockedlist.get (1));
Returns NULL because the return value has not yet been simulated
System.out.println (Mockedlist.get (999));
3. Parameter matching device
Use Anyint () to match any int type parameter Mockito.when (Mockedlist.get (Anyint ())). Toreturn ("element");//You can use your own defined match (IsValid () is a custom parameter-matching device):
Mockito.when (Mockedlist.contains (Argthat (IsValid ())). Toreturn ("element");
public class IsValid extends ArgumentMatcher<Object> {
@Override
public boolean matches(Object argument) {
if (argument instanceof String) {
return true;
} return false;
}
}
Introduction to the Mock tool Mockito in Java