Testing for multiple exceptions with JUnit 4 annotations

后端 未结 7 2303
-上瘾入骨i
-上瘾入骨i 2020-12-30 22:06

Is it possible to test for multiple exceptions in a single JUnit unit test? I know for a single exception one can use, for example

    @Test(expected=Illega         


        
7条回答
  •  无人及你
    2020-12-30 22:23

    This is not possible with the annotation.

    With JUnit 4.7 you can use the new ExpectedException rule

    public static class HasExpectedException {
        @Interceptor
        public ExpectedException thrown= new ExpectedException();
    
        @Test
        public void throwsNothing() {
        }
    
        @Test
        public void throwsNullPointerException() {
             thrown.expect(NullPointerException.class);
             throw new NullPointerException();
        }
    
        @Test
        public void throwsNullPointerExceptionWithMessage() {
            thrown.expect(NullPointerException.class);
            thrown.expectMessage("happened?");
            throw new NullPointerException("What happened?");
        }
    }
    

    More see

    • JUnit 4.7: Interceptors: expected exceptions
    • Rules in JUnit 4.7

    If updating to JUnit 4.7 is not possible for you, you have to write a bare unit test of the form

    public test() {
        try {
            methodCall(); // should throw Exception
            fail();
        }
        catch (Exception ex) {
            assert((ex instanceof A) || (ex instanceof B) || ...etc...);
            ...
        }
    

    }

提交回复
热议问题