Reputation: 41168
So I am trying to mock a method getPremium
that takes a single parameter, an instance of PanicLevel
which is an enum
. It needs to return a different double value depending on the PanicLevel
passed in.
If I want to do this per enum value then something like thi should work.
Mockito.when(mockData.getPremium(PanicLevel.NORMAL)).thenReturn(1.1);
But that needs a line per enum value. I'd much rather do something like:
Mockito.when(mockData.getPremium(anyPanicLevel())).thenReturn(premiums.get(passedInPanicLevel());
Obviously this isn't valid...but something similar should be....
I found this but it uses a method anyString
from somewhere:
mockito return value based on property of a parameter
How do I get Mockito to do this without doing repeated when
for each key?
Upvotes: 2
Views: 3670
Reputation: 140309
You can use an Answer
:
Mockito.when(mockData.getPremium(Matchers.any(PanicLevel.class)))
.thenAnswer(new Answer<Double>() {
@Override
public Double answer(InvocationOnMock arg0) throws Throwable {
PanelLevel panicLevel = (PanicLevel) arg0.getArguments()[0];
return premiums.get(panicLevel);
}
});
FYI: anyString()
is likely just Matchers.anyString()
.
Upvotes: 5
Reputation: 956
Output is dependent on the PanicLevel enum value. Then we need to mock all values that are required for test case. I don't think there is any other way of doing. You can have Properties(enumValue, ouput) then iterate them to achieve this.
Upvotes: 0
Reputation: 7
Mockito: How to match any enum parameter
Looks like you will need to use Matchers.any(Class)
Mockito.when(mockData.getPremium(Matchers.any(PanicLevel.class)).thenReturn(premiums.get(passedInPanicLevel());
Upvotes: -1