在 Java 中使用 Mockito 模拟枚举

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38224517/
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-11-03 03:13:44  来源:igfitidea点击:

Mock an enum using Mockito in Java

javaunit-testingenumsmockito

提问by Arthur Eirich

How can I mock an enum for testing purposes using Mockito? Given this sample for the enum:

如何使用 Mockito 模拟枚举以进行测试?鉴于此枚举示例:

public enum TestEnum {
 YES,
 NO
}

and this one for the method using the enum:

这是使用枚举的方法:

public static boolean WorkTheEnum(TestEnum theEnum) {
switch (theEnum) {
  case YES:
     return true;
  case NO:
     return false;
  default:
     // throws an exception here
 }
}

how can I mock the enum to reach the default branch of the switch loop? This answersays Mockito can't mock enums but the answer has also been provided more than a year ago. Do I can mock an enum meanwhile or have I to let the branch stay untested? Other Mocking frameworks can't be used.

如何模拟枚举以到达 switch 循环的默认分支?这个答案说 Mockito 不能模拟枚举,但一年多前也提供了答案。我可以同时模拟枚举还是让分支保持未经测试?不能使用其他 Mocking 框架。

回答by GhostCat

There are two answers to that:

对此有两个答案:

a) you could turn to some PowerMock-like mocking framework. My two cent(entences) there: don't do that. PowerMock opens a door to the land of pain; which you do not want to enter.

a) 你可以求助于一些类似 PowerMock 的模拟框架。我在那里的两分(entences):不要那样做。PowerMock 打开了通往痛苦之地的大门;您不想输入的内容。

b) put interfaces on your enums

b) 把接口放在你的枚举上

Seriously; I nowadays think that there is only one good use case for enums; and that is to use them as singletons that provide a certain service. And then, I do this:

严重地; 我现在认为枚举只有一个很好的用例;那就是将它们用作提供某种服务的单身人士。然后,我这样做:

public interface FooService { void foo(); }
class FooServiceImpl implements FooService { @Override void foo() ...
enum FooServiceProvider implements FooService {
   INSTANCE;
   private final FooService impl  = new FooServiceImpl();
   @Override foo() { impl.foo()

Of course, this doesn't really help when you use enums like you do. But the thing is: you shouldn't be using enums that way anyway. Because using enums this way leads to shattered code - every place that takes an enum variable is in need for such switch statements; with all the negative consequences when you add / remove enum cases.

当然,当您像这样使用枚举时,这并没有真正的帮助。但问题是:无论如何你都不应该那样使用枚举。因为以这种方式使用枚举会导致代码破碎——每个需要枚举变量的地方都需要这样的 switch 语句;添加/删除枚举案例时会带来所有负面后果。

So, in your case: consider turning to true OO designs - where you have abstract base classes that define methods; and then you use factories to create subclasses (probably based on enum switches) that give you objects that simply do the right thing.

所以,在你的情况下:考虑转向真正的 OO 设计——你有定义方法的抽象基类;然后您使用工厂来创建子类(可能基于枚举开关),这些子类为您提供简单地做正确事情的对象。