I have a method :
public class Sender{
public Object send(Object param){
Object x;
.....
return (x);
}
}
I want to write a unit test for this method using Mockito such that the return type value is based on the class type of the paramter. So I did this:
when(sender.send(Matchers.any(A.class))).thenReturn(value1);
when(sender.send(Matchers.any(B.class))).thenReturn(value2);
but the return value irrespective of the parameter class type is always value 2. How do it get this to return value 1 for class A type argument and value 2 for class B type argument.
when(sender.send(Matchers.any(A.class))).thenReturn(value1);
Mockito will try to mock a method with signature send(A param), not send(Object param).
What you need is to return a different value base on the class of you parameter. You need to use Answers for this.
Mockito.doAnswer(invocationOnMock -> {
if(invocationOnMock.getArguments()[0].getClass() instanceof A) {
return value1;
}
if(invocationOnMock.getArguments()[0].getClass() instanceof B) {
return value2;
}
else {
throw new IllegalArgumentException("unexpected type");
}
}).when(mock).send(Mockito.anyObject());
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