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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With