How do I assert my exception message with JUnit Test annotation?

前端 未结 12 2034
广开言路
广开言路 2020-12-12 08:53

I have written a few JUnit tests with @Test annotation. If my test method throws a checked exception and if I want to assert the message along with the exceptio

12条回答
  •  情书的邮戳
    2020-12-12 09:03

    I like user64141's answer but found that it could be more generalized. Here's my take:

    public abstract class ExpectedThrowableAsserter implements Runnable {
    
        private final Class throwableClass;
        private final String expectedExceptionMessage;
    
        protected ExpectedThrowableAsserter(Class throwableClass, String expectedExceptionMessage) {
            this.throwableClass = throwableClass;
            this.expectedExceptionMessage = expectedExceptionMessage;
        }
    
        public final void run() {
            try {
                expectException();
            } catch (Throwable e) {
                assertTrue(String.format("Caught unexpected %s", e.getClass().getSimpleName()), throwableClass.isInstance(e));
                assertEquals(String.format("%s caught, but unexpected message", throwableClass.getSimpleName()), expectedExceptionMessage, e.getMessage());
                return;
            }
            fail(String.format("Expected %s, but no exception was thrown.", throwableClass.getSimpleName()));
        }
    
        protected abstract void expectException();
    
    }
    

    Note that leaving the "fail" statement within the try block causes the related assertion exception to be caught; using return within the catch statement prevents this.

提交回复
热议问题