Is there a way to spy on parameters passed to a Mocked object in Mockito
Asked Answered
C

1

10

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.

Clayborn answered 5/10, 2015 at 19:1 Comment(0)
P
21

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());
}
Parade answered 5/10, 2015 at 19:34 Comment(2)
is something similar possible for parameters using when() ? Maybe the class Employee is ridiculous to create and I'm only interested in some properties?Hettie
For testing, I recomend using the Test Data Builder 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.Parade

© 2022 - 2024 — McMap. All rights reserved.