3

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.

2 Answers 2

4

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()); 
Sign up to request clarification or add additional context in comments.

3 Comments

Exactly what I was thinking, but too lazy to write :-)
@noscreenname Ahh! Can you convert this to not using the lambda expression please? I understand the intent but unable to replicate it.
@Sherlock123 I could, but so could you if you look up Mockito.doAnswer() documentation ;)
0

A couple options:

  1. Don't use any. Use the instance of A or B you're using in the test.

  2. Use an Answer object, which would allow you to specify what to return.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.