Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito: How to match any enum parameter

I have this method declared like this

private Long doThings(MyEnum enum, Long otherParam); and this enum

public enum MyEnum{   VAL_A,   VAL_B,   VAL_C } 

Question: How do I mock doThings() calls? I cannot match any MyEnum.

The following doesn't work:

Mockito.when(object.doThings(Matchers.any(), Matchers.anyLong()))         .thenReturn(123L); 
like image 348
George D Avatar asked Nov 13 '13 09:11

George D


People also ask

Can you use == for enums?

Because there is only one instance of each enum constant, it is permissible to use the == operator in place of the equals method when comparing two object references if it is known that at least one of them refers to an enum constant.

Can we compare two enums?

There are two ways for making comparison of enum members :equals method uses == operator internally to check if two enum are equal. This means, You can compare Enum using both == and equals method.

How do you compare enums to strings?

For comparing String to Enum type you should convert enum to string and then compare them. For that you can use toString() method or name() method. toString()- Returns the name of this enum constant, as contained in the declaration.


1 Answers

Matchers.any(Class) will do the trick:

Mockito.when(object.doThings(Matchers.any(MyEnum.class), Matchers.anyLong()))     .thenReturn(123L); 

null will be excluded with Matchers.any(Class). If you want to include null you must use the more generic Matchers.any().

As a side note: consider using Mockito static imports:

import static org.mockito.Matchers.*; import static org.mockito.Mockito.*; 

Mocking gets a lot shorter:

when(object.doThings(any(MyEnum.class), anyLong())).thenReturn(123L); 
like image 198
rzymek Avatar answered Sep 18 '22 13:09

rzymek