Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use mockito to mock method with Object parameter

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.

like image 636
Sherlock123 Avatar asked Dec 28 '25 09:12

Sherlock123


1 Answers

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());
like image 188
noscreenname Avatar answered Dec 31 '25 00:12

noscreenname