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

前端 未结 10 1191
甜味超标
甜味超标 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:33

    The following helper method (adapted from this blog post) does the trick:

    /**
     * Run a test body expecting an exception of the
     * given class and with the given message.
     *
     * @param test              To be executed and is expected to throw the exception.
     * @param expectedException The type of the expected exception.
     * @param expectedMessage   If not null, should be the message of the expected exception.
     * @param expectedCause     If not null, should be the same as the cause of the received exception.
     */
    public static void expectException(
            Runnable test,
            Class expectedException,
            String expectedMessage,
            Throwable expectedCause) {
        try {
            test.run();
        }
        catch (Exception ex) {
            assertSame(expectedException, ex.getClass());
            if (expectedMessage != null) {
                assertEquals(expectedMessage, ex.getMessage());
            }
    
            if (expectedCause != null) {
                assertSame(expectedCause, ex.getCause());
            }
    
            return;
        }
    
        fail("Didn't find expected exception of type " + expectedException.getName());
    }
    

    The test code can then invoke this as follows:

    TestHelper.expectException(
            new Runnable() {
                public void run() {
                    classInstanceBeingTested.methodThatThrows();
                }
            },
            WrapperException.class,
            "Exception Message",
            causeException
    );
    

提交回复
热议问题