This post shows how to capture arguments our codes passed to a mock’s method. To do this, a method must accept reference types. Then, we use Mockito.verify() method. Then, pass an instance of ArgumentCaptor to the mock’s method.
Capture Argument In Mockito
Verifying if our codes ran our method is not enough. We want to see the contents of an argument to the method. To do this, we use the ArgumentCaptor class, as follows.
1 | ArgumentCaptor<T> argCaptor= ArgumentCaptor.forClass(T.class); |
Consider the following codes. The instance variables service and record are mock instances. The record mocks the getId() and getStatus() methods. Then, we capture arguments to the processLegalAged method using the ArgumentCaptor class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | @Test public void testProcess_record_record_not_undefined_status_verify_argument() { Mockito.when(record.getId()).thenReturn("1000"); Mockito.when(record.getStatus()).thenReturn("UNDEFINED STATUS"); ArgumentCaptor<PersonRecord> processLegalAgedArgument = ArgumentCaptor.forClass(PersonRecord.class); voidMethodClass.process(record); // We check if getStatus was invoked inOrder.verify(record, Mockito.times(1)).getId(); inOrder.verify(record, Mockito.times(2)).getStatus(); Mockito.verify(service, Mockito.only()).processLegalAged(processLegalAgedArgument.capture()); PersonRecord capturedBean = processLegalAgedArgument.getValue(); Assert.assertTrue(record.getId().equals(capturedBean.getId())); Assert.assertTrue(record.getStatus().equals(capturedBean.getStatus())); } |
Download the Codes
The complete codes are available on this link. I added a new test case in com.turreta.mockito.voidmethod.VoidMethodClassTest.