Mocking Java enum to add a value to test fail case

前端 未结 10 1408
死守一世寂寞
死守一世寂寞 2020-11-28 23:55

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):          


        
10条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-29 00:45

    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.

    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
    }
    

    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
    }
    

    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.

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

提交回复
热议问题