mockito_Mockito ArgumentCaptor, @ Captor notes

Posted by exoskeleton on Sat, 01 Jan 2022 04:37:18 +0100

Article source: https://blog.csdn.net/cunchi4221/article/details/107476971
https://www.journaldev.com/21892/mockito-argumentcaptor-captor-annotation
https://www.jianshu.com/p/adee7d28cb59

mockito

Mockito ArgumentCaptor is used to capture arguments for mocked methods. ArgumentCaptor is used with Mockito verify() methods to get the arguments passed when any method is called. This way, we can provide additional JUnit assertions for our tests.

Mockito ArgumentCaptor is used to capture the parameters of the simulation method. ArgumentCaptor is used with the Mockito verify() method to get the parameters passed when calling any method. This allows us to provide additional JUnit assertions for the test.

Mockito ArgumentCaptor (Mockito ArgumentCaptor)
We can create ArgumentCaptor instance for any class, then its capture() method is used with verify() methods.

We can create an ArgumentCaptor instance for any class and then use its capture() method with the verify() method.

Finally, we can get the captured arguments from getValue() and getAllValues() methods.

Finally, we can get the captured parameters from the getValue() and getAllValues() methods.

getValue() method can be used when we have captured a single argument. If the verified method was called multiple times then getValue() method will return the latest captured value.

When we capture a single parameter, we can use the getValue() method. If the validated method is called multiple times, the getValue() method returns the most recently captured value.

If multiple arguments are captured, call getAllValues() to get the list of arguments.

If multiple parameters are captured, call getAllValues() to get a list of parameters.

Mockito ArgumentCaptor example
Let's say we have a class defined as:

Suppose we have a class defined as:

class MathUtils {
	public int add(int x, int y) {
		return x + y;
	}

	public boolean isInteger(String s) {
		try {
			Integer.parseInt(s);
		} catch (NumberFormatException e) {
			return false;
		}
		return true;
	}
	
	public long squareLong(long l) {
		return l*l;
	}
}

We can write our test case and use ArgumentCaptor as shown below.

We can write test cases and use ArgumentCaptor, as shown below.

@Test
void test() {
	MathUtils mockMathUtils = mock(MathUtils.class);
	when(mockMathUtils.add(1, 1)).thenReturn(2);
	when(mockMathUtils.isInteger(anyString())).thenReturn(true);

	ArgumentCaptor acInteger = ArgumentCaptor.forClass(Integer.class);
	ArgumentCaptor acString = ArgumentCaptor.forClass(String.class);

	assertEquals(2, mockMathUtils.add(1, 1));
	assertTrue(mockMathUtils.isInteger("1"));
	assertTrue(mockMathUtils.isInteger("999"));

	verify(mockMathUtils).add(acInteger.capture(), acInteger.capture());
	List allValues = acInteger.getAllValues();
	assertEquals(List.of(1, 1), allValues);
	
	verify(mockMathUtils, times(2)).isInteger(acString.capture());
	List allStringValues = acString.getAllValues();
	assertEquals(List.of("1", "999"), allStringValues);
}

Mockito @Captor (Mockito @Captor)
We can use @Captor annotation to create argument captor at field level. So instead of initializing field level ArgumentCaptor as:

We can use the @ Captor annotation to create parameter traps at the field level. Therefore, instead of initializing the ArgumentCaptor at the field level to:

ArgumentCaptor acLong = ArgumentCaptor.forClass(Long.class);

We can use @Captor as:

We can use @ Captor as:

@Captor ArgumentCaptor acLong;

Note that we have to call MockitoAnnotations.initMocks(this); before test methods to get it initialized by Mockito framework.

Note that we must call mockitoannotations initMocks(this); Before the test method initialized by the Mockito framework.

Mockito @Captor example (Mockito @Captor Example)
Here is a simple example of @Captor annotation.

This is a simple example of the @ Captor annotation.

class MockitoArgumentCaptorExamples {

	@Captor ArgumentCaptor acLong;

	@Test
	void test() {
		MathUtils mockMathUtils = mock(MathUtils.class);
		when(mockMathUtils.squareLong(2L)).thenReturn(4L);
		assertEquals(4L, mockMathUtils.squareLong(2L));
		verify(mockMathUtils).squareLong(acLong.capture());
		assertTrue(2 == acLong.getValue());
	}
}

Use ArgumentCaptor to capture method parameters for verification

In some scenarios, not only the return value and call of the method need to be verified, but also the parameters of the method passed in after a series of interactions. Then we can use the parameter catcher to capture the parameters of the incoming method for verification to see whether it meets our requirements.

ArgumentCaptor introduction

The ArgumentCaptor object is built through the forClass(Class clazz) method of the ArgumentCaptor object. Then, the parameters of the method can be captured during verification, and finally the captured parameter values can be verified. If the method has multiple parameters to capture validation, you need to create multiple ArgumentCaptor objects for processing.

API for ArgumentCaptor

argument.capture() capture method parameters
argument.getValue() gets the method parameter value. If the method is called multiple times, it will return the last parameter value
argument. The getallvalues () method returns multiple parameter values after multiple calls

Application examples

@Test  
public void argumentCaptorTest() {  
    List mock = mock(List.class);  
    List mock2 = mock(List.class);  
    mock.add("John");  
    mock2.add("Brian");  
    mock2.add("Jim");  
      
    ArgumentCaptor argument = ArgumentCaptor.forClass(String.class);  
      
    verify(mock).add(argument.capture());  
    assertEquals("John", argument.getValue());  
      
    verify(mock2, times(2)).add(argument.capture());  
  
    assertEquals("Jim", argument.getValue());  
    assertArrayEquals(new Object[]{"Brian","Jim"},argument.getAllValues().toArray());  
}  

First, the object that needs to pass in capture parameters to build ArgumentCaptor, in the example, String. Next, call argument. in the parameters of the verify method. Capture () method to capture the input parameters, and then the parameter value is saved in the argument variable. You can use argument Getvalue() get. When an object is called several times, such as the mock2 object, argument. Is called GetValue () gets the parameters of the last call. If you want to get all the parameter values, you can call argument Getallvalues(), which returns a List of parameter values.

Topics: Java