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

前端 未结 12 2011
广开言路
广开言路 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条回答
  •  萌比男神i
    2020-12-12 09:23

    Raystorm had a good answer. I'm not a big fan of Rules either. I do something similar, except that I create the following utility class to help readability and usability, which is one of the big plus'es of annotations in the first place.

    Add this utility class:

    import org.junit.Assert;
    
    public abstract class ExpectedRuntimeExceptionAsserter {
    
        private String expectedExceptionMessage;
    
        public ExpectedRuntimeExceptionAsserter(String expectedExceptionMessage) {
            this.expectedExceptionMessage = expectedExceptionMessage;
        }
    
        public final void run(){
            try{
                expectException();
                Assert.fail(String.format("Expected a RuntimeException '%s'", expectedExceptionMessage));
            } catch (RuntimeException e){
                Assert.assertEquals("RuntimeException caught, but unexpected message", expectedExceptionMessage, e.getMessage());
            }
        }
    
        protected abstract void expectException();
    
    }
    

    Then for my unit test, all I need is this code:

    @Test
    public void verifyAnonymousUserCantAccessPrivilegedResourceTest(){
        new ExpectedRuntimeExceptionAsserter("anonymous user can't access privileged resource"){
            @Override
            protected void expectException() {
                throw new RuntimeException("anonymous user can't access privileged resource");
            }
        }.run(); //passes test; expected exception is caught, and this @Test returns normally as "Passed"
    }
    

提交回复
热议问题