mockito Getting started with mockito Check arguments passed to mock


Example

Lets assume we have this class and we would like to test doSmth method. In this case we want to see if parameter "val" is passed to foo. Object foo is mocked.

public class Bar {

    private final Foo foo;

    public Bar(final Foo foo) {
        this.foo = foo;
    }

    public void doSmth() {
        foo.bla("val");
    }
}

We can achieve this with ArgumentCaptor:

@Mock
private Foo fooMock;

@InjectMocks
private Bar underTest;

@Captor
private ArgumentCaptor<String> stringCaptor;

@Test
public void should_test_smth() {
    underTest.doSmth();

    Mockito.verify(fooMock).bla(stringCaptor.capture());

    assertThat(stringCaptor.getValue(), is("val"));
}