Search code examples
javajunitmockitopowermockito

Save information that was spied by Mockito


I have a JUnit test as:

@Spy
ParallelSender parallelSender = new ParallelSender();


@Test
public void send() {   
    // making some data...
    parallelSender.send(someData);
    // check that internal method has been called with Sender Task made from someData
    verify(parallelSender).doSend(any(SenderTask.class));
}

I however like to examine that SenderTask contains all the fields exactly as I need them. Can I tell the spy to intercept the doSend call, store its parameters in some array and then continue to real method?


Solution

  • Use the ArgumentCaptor:

    @Test
    public void send() {   
        // making some data...
        parallelSender.send(someData);
    
       // Define the captor for class
        ArgumentCaptor<SenderTask> captor =
            ArgumentCaptor.forClass(SenderTask.class);
    
        // Capture input while verifying
        verify(parallelSender).doSend(captor.capture());
    
        // Assert 
        SomeTask result = captor.getValue();
        // assertions on result
    }