6

I have a service that I am mocking using Mockito. Is there any way that I can verify the parameters passed to the service call?

For example:

I have a service named employeeAnalyzer.calculateAnnualAppraisalForEmployee(Employee emp).

So from unit test I would like to do something like

verifyThat ("John", emp.getName());
verifyThat ("Doe", emp.getLastName);

Basically I want to spy on the parameter that was sent to the service which I inject using

@InjectMocks
EmployeeAnalyzer employeeAnalyzer;

Thanks in advance.

Callum Watkins
  • 2,844
  • 4
  • 29
  • 49
john.p.doe
  • 411
  • 2
  • 10
  • 21

1 Answers1

17

Definitely! Mockito is awesome. You can use an ArgumentCaptor to capture the Employee parameter and then do some assertions.

(example taken from the previous link)

ArgumentCaptor<Person> argument = ArgumentCaptor.forClass(Person.class);
verify(mock).doSomething(argument.capture());
assertEquals("John", argument.getValue().getName());

Or the new funky way using the @Captor annotation

@Captor ArgumentCaptor<AsyncCallback<Foo>> captor;

@Before
public void init(){
   MockitoAnnotations.initMocks(this);
}

@Test public void shouldDoSomethingUseful() {
   //...
   verify(mock).doStuff(captor.capture());
   assertEquals("foo", captor.getValue());
}
alessiosavi
  • 2,753
  • 2
  • 19
  • 38
Augusto
  • 28,839
  • 5
  • 58
  • 88
  • is something similar possible for parameters using `when()` ? Maybe the class `Employee` is ridiculous to create and I'm only interested in some properties? – Lusk116 Apr 11 '22 at 09:24
  • For testing, I recomend using the [Test Data Builder](http://natpryce.com/articles/000714.html) pattern. Makes it easy to create templated objects that you can later tailor in your tests. And if a class is too difficult to build, it screams that there's a problem with the design. As a rule of thumb is a bad idea to mock entities and value objects. – Augusto Apr 11 '22 at 11:13