Reputation: 913
I have a junit test in which I have an object mocked within a class. Let's call the class Mocker
with the @Mock of MyManager called mocker
.
Example class:
public class Mocker {
private MyManager myManager;
public void myMethod() {
String x = "test";
final String result1 = this.myManager.execute(dummyEnum.ENUM_A, x);
final String result2 = this.myManager.execute(dummyEnum.ENUM_B, x);
if(result1 == true) {
//Do something
}
if(result2 == true) {
//Do something else
}
}
public enum dummyEnum {
ENUM_A,ENUM_B
}
}
My current junit test uses the following: doReturn(null).when(mocker).execute(any(dummyEnum.class), anyObject());
However, this will return null for both result1 & result2. How can I specify that when execute() is executed with ENUM_A it returns a String of Hello
and execute() with ENUM_B returns a String of Goodbye
I have seen the answer here but I don't want to just say any instance of that class, I want to specify a certain enum from that class.
Upvotes: 4
Views: 6392
Reputation: 131316
I have seen the answer here but I don't want to just say any instance of that class, I want to specify a certain enum from that class.
In your case just pass the enum instance :
import static org.mockito.Mockito.*;
...
Mockito.doReturn(null).when(mocker).execute(eq(DummyEnum.ENUM_A), any());
Mockito.doReturn(null).when(mocker).execute(eq(DummyEnum.ENUM_B), any());
Note 1 : any()
should be used only as you don't have the choice or that the value doesn't matter (which is rarely the case).
Note 2: avoid Matchers
class. Use ArgumentMatchers
instead.
From Mockito 2, this class is deprecated in order to avoid a name clash with Hamcrest org.hamcrest.Matchers
class and javadoc also states this class will likely be removed in version 3.0.
Upvotes: 3
Reputation: 7862
Use the eq()
methods (which stands for equals) of the Matchers class.
Mockito.doReturn("Hello").when(mock).execute(Matchers.eq(dummyEnum.ENUM_A), anyObject());
Mockito.doReturn("Goodbye").when(mock).execute(Matchers.eq(dummyEnum.ENUM_B), anyObject());
Upvotes: 6