Reputation: 15008
Assume we have the following class:
class Person {
private int age;
private String name;
public Person(int age, String name){
this.age = age;
this.name = name;
}
// getters and setters
}
and we also have some class:
class SpecialClass {
public int giveNumber(Person p) {
...
return (int)(...)
}
}
Assume I want to mock an object of SpecialClass that if 'giveNumber' is invoked with a Person object that has name property equals to 'John', then 'giveNumber' will retrieve 500.
For example,
SpecialClass sc = mock(SpecialClass.class);
when(sc.giveNumber(p with name = "John").thenReturn(500);
Is there any way to do it with Mockito?
Upvotes: 4
Views: 2427
Reputation: 728
You can use org.mockito.ArgumentMatchers.argThat(...)
passing it a lambda that matches the desired instance. In this case the lamdba would be something like
(person) -> "John".equals(person.getName())
Putting it together:
SpecialClass sc = mock(SpecialClass.class);
when(sc.giveNumber(argThat((person) -> "John".equals(person.getName())))).thenReturn(500);
Upvotes: 9