JUnit 4 Expected Exception type

前端 未结 4 1946
無奈伤痛
無奈伤痛 2020-12-08 06:54

I am trying to do a JUnit test on code that someone else has written, but I cannot figure out how to test for the exception, because the exception seems to lack a type.

4条回答
  •  一生所求
    2020-12-08 07:23

    You could either use expected in @Test annotation or provide an explicit catch block and issue a fail if the program flow is not as expected.

    @Test(expected=Exception.class) // java.lang.Exception
    public static void exceptionTest() throws Exception {
        rodgers = new Pirate("Dread Pirate Rodgers" , -100);
    }
    
    @Test
    public static void exceptionTest() throws Exception {
        try {
            rodgers = new Pirate("Dread Pirate Rodgers" , -100);
            fail("should not reach this");
        } catch(Exception e) {
            // ok
        }
    }
    

    My personal preference is the first solution.

提交回复
热议问题