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);
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With