'Mockito: verify function being called with an argument that has deep nested objects
I have this class and a unit test to verify a function being called with an argument which is a list of objects that has nested objects.
@Data
class Test {
private String name;
private User user;
}
@Data
class User {
private String name;
}
service.somemethod(List.of(
new Test("test1", new User("user1")),
new Test("test1", new User("user1"))
));
My test code:
Service spyService = Mockito.spy(service);
verify(spyService, times(1)).somemethod(eq(List.of(
new Test("test1", new User("user1")),
new Test("test1", new User("user1"))
)));
This will give me an error that User does not match. I see it is trying to compare User by address instead of value. How can I make it so that it will compare the nested object by value? I tried adding eq() around new User() but it throws another error saying eq can't be used there
Solution 1:[1]
if you create seprate list variable and passed it to the spied function and to the verify function it will work:
@Test
public void test_spy_2() {
BusinessImpl businessImpl_spied = spy(BusinessImpl.class);
List<Depratment> list = List.of(
new Test("test1", new User("user1")),
new Test("test1", new User("user1"))
);
businessImpl_spied.testCallList(list);
verify(businessImpl_spied).testCallList(ArgumentMatchers.eq(list));
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | tricksSpecialist |
