模拟Java枚举以添加一个值来测试失败案例 [英] Mocking Java enum to add a value to test fail case
问题描述
我有一个或多个这样的开关:
I have an enum switch more or less like this:
public static enum MyEnum {A, B}
public int foo(MyEnum value) {
switch(value) {
case(A): return calculateSomething();
case(B): return calculateSomethingElse();
}
throw new IllegalArgumentException("Do not know how to handle " + value);
}
我想让测试覆盖所有的行,但因为代码预期会处理所有的可能性,所以我不能在交换机中提供没有相应的case语句的值。
and I'd like to have all the lines covered by the tests, but as the code is expected to deal with all possibilities, I cannot supply a value without its corresponding case statement in the switch.
扩展枚举以添加额外的值不是可能的,只是嘲笑equals方法返回 false
将无法正常工作,因为生成的字节码使用窗帘后面的跳转表去适当的情况...所以我以为可能有一些黑魔法可以用PowerMock或某些东西来实现。
Extending the enum to add an extra value is not possible, and just mocking the equals method to return false
won't work either because the bytecode generated uses a jump table behind the curtains to go to the proper case... So I've thought that maybe some black magic could be achieved with PowerMock or something.
谢谢!
strong>编辑:
edit:
由于我拥有枚举,我以为我可以添加一个方法到值,从而避免交换机的问题;但是我仍然会留下这个问题,因为它仍然是有趣的。
As I own the enumeration, I've thought that I could just add a method to the values and thus avoid the switch issue completely; but I'm leaving the question as it's still interesting.
推荐答案
Java专家通讯有一个问题( http://www.javaspecialists.eu/archive/Issue161.html ),试图解决这种问题。它涉及各种反思魔法和SUN内部类的使用。我承认我没有完全阅读,但也许这对你有兴趣?
There's an issue of the Java Specialists newsletter (http://www.javaspecialists.eu/archive/Issue161.html) that tried to tackle this kind of problem. It involves all kinds of reflection magic and usage of SUN internal classes. I admit that I haven't read it completely, but maybe it's of interest to you?
这篇关于模拟Java枚举以添加一个值来测试失败案例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!