In Java how can I validate a thrown exception with JUnit?

前端 未结 10 1193
甜味超标
甜味超标 2020-11-30 05:47

When writing unit tests for a Java API there may be circumstances where you want to perform more detailed validation of an exception. I.e. more than is offered by the @t

10条回答
  •  情歌与酒
    2020-11-30 06:13

    In JUnit 4 it can be easily done using ExpectedException rule.

    Here is example from javadocs:

    // These tests all pass.
    public static class HasExpectedException {
        @Rule
        public ExpectedException thrown = ExpectedException.none();
    
        @Test
        public void throwsNothing() {
            // no exception expected, none thrown: passes.
        }
    
        @Test
        public void throwsNullPointerException() {
            thrown.expect(NullPointerException.class);
            throw new NullPointerException();
        }
    
        @Test
        public void throwsNullPointerExceptionWithMessage() {
            thrown.expect(NullPointerException.class);
            thrown.expectMessage("happened?");
            thrown.expectMessage(startsWith("What"));
            throw new NullPointerException("What happened?");
        }
    }
    

提交回复
热议问题