Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use ArgumentCaptor for stubbing?

In Mockito documentation and javadocs it says

It is recommended to use ArgumentCaptor with verification but not with stubbing.

but I don't understand how ArgumentCaptor can be used for stubbing. Can someone explain the above statement and show how ArgumentCaptor can be used for stubbing or provide a link that shows how it can be done?

like image 386
Can't Tell Avatar asked Sep 06 '12 08:09

Can't Tell


People also ask

What is the use of ArgumentCaptor?

ArgumentCaptor allows us to capture an argument passed to a method to inspect it. This is especially useful when we can't access the argument outside of the method we'd like to test.

Which annotation is used to create an ArgumentCaptor?

We can use @Captor annotation to create argument captor at field level.


1 Answers

Assuming the following method to test:

public boolean doSomething(SomeClass arg);

Mockito documentation says that you should not use captor in this way:

when(someObject.doSomething(argumentCaptor.capture())).thenReturn(true);
assertThat(argumentCaptor.getValue(), equalTo(expected));

Because you can just use matcher during stubbing:

when(someObject.doSomething(eq(expected))).thenReturn(true);

But verification is a different story. If your test needs to ensure that this method was called with a specific argument, use ArgumentCaptor and this is the case for which it is designed:

ArgumentCaptor<SomeClass> argumentCaptor = ArgumentCaptor.forClass(SomeClass.class);
verify(someObject).doSomething(argumentCaptor.capture());
assertThat(argumentCaptor.getValue(), equalTo(expected));
like image 146
Rorick Avatar answered Sep 25 '22 10:09

Rorick