【问题标题】:Mockito: How to match any enum parameterMockito:如何匹配任何枚举参数
【发布时间】:2013-11-13 09:15:09
【问题描述】:

我有这样声明的方法

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

public enum MyEnum{
  VAL_A,
  VAL_B,
  VAL_C
}

问题:如何模拟 doThings() 调用? 我无法匹配任何MyEnum。

以下不起作用:

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

【问题讨论】:

    标签: java enums mockito


    【解决方案1】:

    Matchers.any(Class) 可以解决问题:

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

    null 将被排除在 Matchers.any(Class) 之外。如果你想包含null,你必须使用更通用的Matchers.any()。

    附带说明:考虑使用 Mockito 静态导入:

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

    模拟变得更短:

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

    【讨论】:

    • 添加静态导入要好得多:)
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2011-11-21
      • 2018-09-15
      • 2015-03-17
      • 2011-12-21
      • 2012-09-23
      • 1970-01-01
      • 2016-02-28
      相关资源
      最近更新 更多