简体   繁体   English

如何让Mockito根据枚举返回不同的值?

[英]How do I get Mockito to return different values based on an enum?

So I am trying to mock a method getPremium that takes a single parameter, an instance of PanicLevel which is an enum . 因此,我试图模拟一个采用单个参数的PanicLevel方法,该方法是getPremium一个实例,该实例是一个enum It needs to return a different double value depending on the PanicLevel passed in. 它需要根据传入的PanicLevel返回不同的double值。

If I want to do this per enum value then something like thi should work. 如果我想按枚举值执行此操作,则应使用thi之类的方法。

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 我发现了它,但是它从某处使用了方法anyString基于参数属性的 anyString 返回值

How do I get Mockito to do this without doing repeated when for each key? 如何让Mockito做到这一点,而不必为每个键重复when

You can use an Answer : 您可以使用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() . 仅供参考: anyString()可能只是anyString() Matchers.anyString()

Output is dependent on the PanicLevel enum value. 输出取决于PanicLevel枚举值。 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. 您可以具有Properties(enumValue,ouput),然后对其进行迭代以实现此目的。

Mockito: How to match any enum parameter Mockito:如何匹配任何枚举参数

Looks like you will need to use Matchers.any(Class) 看起来您将需要使用Matchers.any(Class)

Mockito.when(mockData.getPremium(Matchers.any(PanicLevel.class)).thenReturn(premiums.get(passedInPanicLevel());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM