Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specify specific enum being passed into method in Mockito doReturn method

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.

like image 712
DevelopingDeveloper Avatar asked Jan 29 '23 00:01

DevelopingDeveloper


1 Answers

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());
like image 111
Anthony Raymond Avatar answered Feb 08 '23 14:02

Anthony Raymond