Example of Mockito's argumentCaptor

Ujjwal picture Ujjwal · Mar 27, 2016 · Viewed 140.2k times · Source

Can anyone please provide me an example showing how to use the org.mockito.ArgumentCaptor class and how it is different from simple matchers that are provided with mockito.

I read the provided mockito documents but those doesn't illustrate it clearly, none of them are able to explain it with clarity.

Answer

Slava Shpitalny picture Slava Shpitalny · Mar 28, 2016

I agree with what @fge said, more over. Lets look at example. Consider you have a method:

class A {
    public void foo(OtherClass other) {
        SomeData data = new SomeData("Some inner data");
        other.doSomething(data);
    }
}

Now if you want to check the inner data you can use the captor:

// Create a mock of the OtherClass
OtherClass other = mock(OtherClass.class);

// Run the foo method with the mock
new A().foo(other);

// Capture the argument of the doSomething function
ArgumentCaptor<SomeData> captor = ArgumentCaptor.forClass(SomeData.class);
verify(other, times(1)).doSomething(captor.capture());

// Assert the argument
SomeData actual = captor.getValue();
assertEquals("Some inner data", actual.innerData);