mockito for java unit testing

Posted by MoldRat on Sat, 06 Nov 2021 05:51:38 +0100

Learn mockito

1: Introduction to mockito

Mockito is an excellent mock framework for unit testing. When "mock" is mentioned in software development, it is usually understood as a simulation object. So mockito is to simulate the object and then conduct decoupling test.
Mock is to make a fake object. All calls to the methods in this object will be intercepted by the fake object that has been mock, and then return to the user's preset behavior.

1.1: basic use

Basic steps for integrating Mockito

Mark the class or object mock (simulated) to generate a proxy object@ Mock generates a fake object from the object pair labeled.
Customize the behavior of proxy objects through the Mockito API
Call the method of the proxy object to obtain the pre-designed results

1.2: Syntax

1: mock simulation

Implement simulated objects
Method 1: use mock

//Simulate creating a List object
        List mock = mock(List.class);

Method 2: use the Mockito class

 public void testMockSecond(){
        List mock = Mockito.mock(List.class);
        mock.add(1);
        System.out.println(mock.size());
        assertEquals(mock.size(),0);
    }

Method 3: use @ mock annotation

//Specify runner
@RunWith(MockitoJUnitRunner.class)
public class MockitoTestSecond {
    List one=new ArrayList();  //Create objects normally
    @Mock     //Annotate simulated objects
    List list;

    @Test
    public void one() {
        list.add(1);
        System.out.println(list.size());
        new MockitoTestSecond().one.add(1);
    }
}

mock reset will clear all scheduled actions and values

   List mock = mock(List.class);
        reset(mock);

2: When thenreturn scheduled expected action

Sets the expected return value when the action occurs

    @Test
    public void when_thenReturnTwo(){
        ArrayList mock = Mockito.mock(ArrayList.class);
        Scheduled when mock.add(1)Return on action true,All subsequent actions return false
        when(mock.add(1)).thenReturn(true).thenReturn(false);
        boolean add = mock.add(1);   //Expected true
        boolean add1 = mock.add(2);   //The expectation is false
        System.out.println(add+"--"+add1);   //Result true--false
}

3: When then throw and doThrow expectations are abnormal

As the name suggests: when something happens, what exception is thrown.
doThrow: used for methods with no return value
thenThrow: used for methods with return values

  @Test
    public void when_thenThrow3(){
        ArrayList mock = Mockito.mock(ArrayList.class);
       when(mock.add(1)).thenThrow(new RuntimeException());
        doThrow(new RuntimeException()).when(mock).clear();
        mock.add(1);
        mock.clear();
    }

4: when_thenAnswer expects the result to be returned

When an action occurs, the expected result is

     @Test
    public void when_thenAnswer(){
        ArrayList mock = Mockito.mock(ArrayList.class);
        when(mock.add(1)).thenAnswer(new Answer<Object>() {
            @Override
            public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
                return true;   //The mock.add(1) action is expected to return true
            }
        });
        boolean add = mock.add(1);
      assertEquals(add,true);     //Using junit's assertion judgment
    }

5: . verify (verify interaction)

Check whether the interaction behavior occurs. It is a Boolean type. The default is false. As long as no exceptions are found, the behavior is normal., You can pass in the timeout parameter for timeout verification.

 @Test
    public void testMockFour(){
        ArrayList mock = Mockito.mock(ArrayList.class);
        mock.add(1); //Because it is a simulated list, 1 is not added to the actual mock
        //Use verify for interactive verification to determine whether the add action occurs
        Boolean verify = verify(mock).add(2);  
         verify(mock,timeout(10)).add(1); //Perform timeout efficiency verification
        //It can be seen that it is still false and no exception is thrown, that is, the add behavior is normal under normal circumstances
        System.out.println(verify);
    }

6: spy real data

Using spy to monitor real objects will call the API to execute. mock is simulated and does not execute the API. Pay attention to the difference between the two.
It should be noted that at this time, we need to carefully use the when-then statement instead of the do-when statement
When then will execute the api, but do when will not, so do when cannot be used in combination with mock (mock will not execute the api originally)

/*spy Execution will formally call the api to execute, which is different from mock simulation*/
    @Test
    public void testSpy(){
        //Using spy to simulate real data
        ArrayList<Object> objects = new ArrayList<>();
        List spy = spy(objects);
        when(spy.add(1)).thenReturn(true);
        //
        doReturn(false).when(spy).add(2);
        boolean add1 = spy.add(1);
        boolean add2 = spy.add(2);
        System.out.println(spy.size()+""+add1+"+"+add2);   //1

        List mock = mock(List.class);
        when(mock.add(1)).thenReturn(true);
       // doReturn(false).when(mock.add(2));   //mock objects are simulated. doreturn cannot be used
        //Objects using mock
        boolean add = mock.add(1);
        boolean add3 = mock.add(2);
        System.out.println(mock.size()+""+add+""+add3);      // 0
    }

result

1true+false
0truefalse

2: Use case

2.1: import dependency

mockito needs to be used with junit

    <dependency>
      <groupId>org.mockito</groupId>
      <artifactId>mockito-core</artifactId>
      <version>4.0.0</version>
      <scope>test</scope>
    </dependency>
     <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.13.2</version>
      <scope>test</scope>
    </dependency>

Simple validation use

@Test
    public void testMockitoFirst(){
        //Simulate creating a List object
        List mock = mock(List.class);
        //Objects using mock
        mock.add(1);
        System.out.println(mock.size());        //0
        mock.clear();
        //Verify that the add(1) and clear() behaviors occur
        verify(mock).add(1);
        verify(mock).clear();
    }

Topics: Java unit testing