0

I am using Mockito for unit testing. And there are many matchers like anyString(), anyBoolean() in Mockito. But suppose if I have a custom enum like

Enum LoginType.java

//LoginType.java
public enum LoginType {
    FACEBOOK,
    EMAIL,
    GOOGLE
}

In one of the method arguments I need to pass an instance of LoginType. How do I pass the argument without explicitly passing LoginType.FACEBOOK or LoginType.GOOGLE. Something like anyString(). Any hint in that direction will be useful.

dur
  • 15,689
  • 25
  • 79
  • 125
thedarkpassenger
  • 7,158
  • 3
  • 37
  • 61

1 Answers1

2

For any behavior, just calling Matchers.any() may be good enough on Java 8. That's when parameter type inference came out.

You might also choose Matchers.any(LoginType.class), which has pure any() behavior in Mockito 1.x but will provide type checking in Mockito 2.0 and beyond. In either case, passing in the class literal will help Java get the type information you need for inference.


For related problems:

  • If you have a generic type, the class literal isn`t enough either; you need to specify it as an explicit method parameter:

    Matchers.<YourContainer<YourType>>any();
    

    ...or extract to a static helper method, which you need to do instead of a constant or local variable because Mockito matchers work via side effects:

    public static LoginType anyLoginType() {
      return Matchers.any();
    }
    
  • Finally, for future readers who might be here to implement custom matching logic, look for Matchers.argThat or MockitoHamcrest.argThat to adapt a Hamcrest-style Matcher object into a Mockito method call.

Community
  • 1
  • 1
Jeff Bowman
  • 90,959
  • 16
  • 217
  • 251