問(wèn)題描述
我有一個(gè) enum 開(kāi)關(guān)或多或少像這樣:
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);
}
我希望測(cè)試涵蓋所有行,但由于代碼需要處理所有可能性,如果沒(méi)有相應(yīng)的 switch 語(yǔ)句,我無(wú)法提供值.
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.
擴(kuò)展枚舉以添加額外的值是不可能的,并且僅僅模擬 equals 方法以返回 false
也不起作用,因?yàn)樯傻淖止?jié)碼使用窗簾后面的跳轉(zhuǎn)表去正確的情況......所以我認(rèn)為也許可以使用 PowerMock 或其他東西來(lái)實(shí)現(xiàn)一些黑魔法.
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.
謝謝!
編輯:
由于我擁有枚舉,我認(rèn)為我可以只為值添加一個(gè)方法,從而完全避免切換問(wèn)題;但我要留下這個(gè)問(wèn)題,因?yàn)樗匀缓苡腥?
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 作為構(gòu)建系統(tǒng),您可以使用更簡(jiǎn)單的方法.只需在測(cè)試類(lèi)路徑中使用附加常量定義相同的枚舉.
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.
假設(shè)您在源目錄 (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
}
現(xiàn)在您在測(cè)試源目錄 (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è)試使用重載"枚舉查看 testclass 路徑,您可以使用C"枚舉常量測(cè)試您的代碼.你應(yīng)該會(huì)看到你的 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 測(cè)試
Tested under windows with maven 3.5.2, AdoptOpenJDK 11.0.3 and IntelliJ IDEA 2019.3.1
這篇關(guān)于模擬 Java 枚舉以添加一個(gè)值來(lái)測(cè)試失敗案例的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!