Java Mockito:如何匹配任何枚举参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19949762/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 21:46:08  来源:igfitidea点击:

Mockito: How to match any enum parameter

javaenumsmockito

提问by George D

I have this method declared like this

我有这样声明的方法

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

private Long doThings(MyEnum enum, Long otherParam);和这个枚举

public enum MyEnum{
  VAL_A,
  VAL_B,
  VAL_C
}

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

问题:如何模拟doThings()通话?我无法匹配任何MyEnum.

The following doesn't work:

以下不起作用:

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

采纳答案by rzymek

Matchers.any(Class)will do the trick:

Matchers.any(Class)会做的伎俩:

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

As a side note: consider using Mockitostatic imports:

作为旁注:考虑使用Mockito静态导入:

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

Mocking gets a lot shorter:

模拟变得更短:

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

回答by VinayVeluri

Apart from the above solution try this...

除了上述解决方案,试试这个......

when(object.doThings((MyEnum)anyObject(), anyLong()).thenReturn(123L);