模拟 Java 枚举以添加值来测试失败案例 [英] Mocking Java enum to add a value to test fail case

查看:25
本文介绍了模拟 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 中提供没有相应 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.

谢谢!

编辑:

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

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
}

测试看到带有重载"枚举的测试类路径,您可以使用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

这篇关于模拟 Java 枚举以添加值来测试失败案例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆