Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito: how to mock an object that has certain property value

Tags:

java

mockito

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?

like image 970
CrazySynthax Avatar asked Oct 22 '25 07:10

CrazySynthax


1 Answers

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);
like image 147
Benjamin Eckardt Avatar answered Oct 23 '25 21:10

Benjamin Eckardt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!