Use mockito to mock method with Object parameter

12,578

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());
Share:
12,578
Sherlock123
Author by

Sherlock123

Updated on June 04, 2022

Comments

  • Sherlock123
    Sherlock123 almost 2 years

    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.