模拟 Java 枚举以添加一个值来测试失败案例

我有一个 enum 开关或多或少像这样:

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);
}

我希望测试涵盖所有行,但由于代码需要处理所有可能性,如果没有相应的 switch 语句,我无法提供值.

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.

谢谢!

编辑:

由于我拥有枚举,我认为我可以只为值添加一个方法,从而完全避免切换问题;但我要留下这个问题,因为它仍然很有趣.

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.

推荐答案

如果您可以使用 Maven 作为构建系统,您可以使用更简单的方法.只需在测试类路径中使用附加常量定义相同的枚举.

If you can use Maven as your build system, you can use a much simpler approach. Just define the same enum with an additional constant in your test classpath.

假设您在源目录 (src/main/java) 下声明了枚举,如下所示:

Let's say you have your enum declared under the sources directory (src/main/java) like this:

package my.package;

public enum MyEnum {
    A,
    B
}

现在您在测试源目录 (src/test/java) 中声明完全相同的枚举,如下所示:

Now you declare the exact same enum in the test sources directory (src/test/java) like this:

package my.package

public enum MyEnum {
    A,
    B,
    C
}

测试使用重载"枚举查看 testclass 路径,您可以使用C"枚举常量测试您的代码.你应该会看到你的 IllegalArgumentException.

The tests see the testclass path with the "overloaded" enum and you can test your code with the "C" enum constant. You should see your IllegalArgumentException then.

在 windows 下使用 maven 3.5.2、AdoptOpenJDK 11.0.3 和 IntelliJ IDEA 2019.3.1 测试

Tested under windows with maven 3.5.2, AdoptOpenJDK 11.0.3 and IntelliJ IDEA 2019.3.1

相关文章