mockito short tutorial

1 overview of mockito

Mockito is a mocking framework that tastes really good. It lets you write beautiful tests with a clean & simple API. Mockito doesn't give you hangover because the tests are very readable and they produce clean verification errors.

Mockito is a very good simulation framework. It allows you to write beautiful tests using clean and simple API s. Mockito won't bother you because these tests are readable and produce clear validation errors.

Official note - how brief version

Official mockito documentation - detailed version

Features and motivations github description

Its characteristics are as follows:

  • mock specific classes and interfaces;
  • Little notes grammar sugar - @ Mock
  • Validation errors are clean - click the stack trace to see the validation that failed in the test; click the reason for the exception to navigate to the actual interaction in the code. The stack trace is always clean.
  • Allow flexible validation in order (for example, validation in order, not every interaction)
  • Support accurate times and at least one verification
  • Flexible validation or stubs using parameter matchers (anyObject(), anyString(), or refEq() for reflection based equality matching)
  • Allows you to create a custom parameter matcher or use an existing hancrest matcher

2 mockito application

The relevant configuration of gradle warehouse is as follows:

repositories { jcenter() }
dependencies { testCompile "org.mockito:mockito-core:2.+" }

For the configuration of maven, you can search for the dependency of adding pom;

2.1 verification interaction

import static org.mockito.Mockito.*;

// mock creation
List mockedList = mock(List.class);

// using mock object - it does not throw any "unexpected interaction" exception
mockedList.add("one");
mockedList.clear();

// selective, explicit, highly readable verification
verify(mockedList).add("one");
verify(mockedList).clear();

2.2 stub method call

// you can mock concrete classes, not only interfaces
LinkedList mockedList = mock(LinkedList.class);

// stubbing appears before the actual execution
when(mockedList.get(0)).thenReturn("first");

// the following prints "first"
System.out.println(mockedList.get(0));

// the following prints "null" because get(999) was not stubbed
System.out.println(mockedList.get(999));

2.3 use of mock annotation

  public class ArticleManagerTest {

       @Mock private ArticleCalculator calculator;
       @Mock private ArticleDatabase database;
       @Mock private UserProvider userProvider;

       private ArticleManager manager;

2.4 callbacks

 when(mock.someMethod(anyString())).thenAnswer(
     new Answer() {
         public Object answer(InvocationOnMock invocation) {
             Object[] args = invocation.getArguments();
             Object mock = invocation.getMock();
             return "called with arguments: " + Arrays.toString(args);
         }
 });

 //Following prints "called with arguments: [foo]"
 System.out.println(mock.someMethod("foo"));
 

2.* more

For more information, see the details document Official mockito documentation - detailed version

3 verify

Mockito provides the verify keyword to verify whether the method is called. Its specific functions can be summarized as follows:

  • Test whether the method is called;
  • The specific call times of vervify(mock, times);
 @Test
    public void update() throws Exception {
        boolean result = personService.update(1, "new name");
        //Verify that getPeron for mockDao has never been called
        verify(mockDao,never()).getPerson(1);
 				assertTrue("must true", result);
    		//Verify getperson has been executed once (1)
    		verify(mockDao, times(1)).getPerson(eq(1));
    		//Verify that an update has been performed once
    		verify(mockDao, times(1)).update(isA(Person.class));
}

However, it should be noted that the use of verify is limited to the mack object, and correlation detection is not supported for ordinary objects, otherwise related errors will be triggered.

 Argument passed to verify() is of type RegistrationMgrActor and is not a mock!
Make sure you place the parenthesis correctly!
See the examples of correct verifications:
    verify(mock).someMethod();
    verify(mock, times(10)).someMethod();
    verify(mock, atLeastOnce()).someMethod();
org.mockito.exceptions.misusing.NotAMockException: 
Argument passed to verify() is of type RegistrationMgrActor and is not a mock!
Make sure you place the parenthesis correctly!
See the examples of correct verifications:
    verify(mock).someMethod();
    verify(mock, times(10)).someMethod();
    verify(mock, atLeastOnce()).someMethod();
	at *******************
1 test completed, 1 failed
FAILURE: Build failed with an exception.
* What went wrong:

The difference between mock and spy

In the project, some functions need to process the return results of a certain service, while those services cannot be started during the function unit test. Here you can use the Mockito tool. Both Mock and Spy in Mockito can be used to intercept and set custom behavior for objects and methods that have not been implemented or are not expected to be called. The differences between them are as follows:

1. For the object declared by mock, all calls to the function execute mock (i.e. false function), and the real part is not executed.

2. The objects declared by Spy and the calls to the functions execute the real part.

Published 89 original articles, won praise 17, visited 40000+
Private letter follow

Tags: github Gradle Maven calculator

Posted on Sun, 02 Feb 2020 04:45:32 -0500 by jennyp