JUnit right way of test expected exceptions

后端 未结 4 1095
走了就别回头了
走了就别回头了 2020-12-15 20:37

Hello guys I was wondering if this way of testing my exception is ok, i have this exception i need to throw in the second test annotation, im receiving as result a red evil

4条回答
  •  情深已故
    2020-12-15 20:56

    There is 3 most common ways to test expected exception:

    First one is the most common way, but you can test only the type of expected exception with it. This test will fail if ExceptionType won't be thrown:

    @Test(expected = ExceptionType.class)
    public void testSomething(){
        sut.doSomething();
    }
    

    Also you cannot specify the failure message using this approach

    The better option is to use ExpectedException JUnit @Rule. Here you can assert much more for expected exception

    @Rule
    public ExpectedException thrown = ExpectedException.none();
    
    @Test
    public void testSomething(){
        thrown.expect(ExceptionType.class);
        thrown.expectMessage("Error message");
        thrown.expectCause(is(new CauseOfExeption()));
        thrown.reportMissingExceptionWithMessage("Exception expected"); 
        //any other expectations
        sut.doSomething();
    }
    

    The third option will allow you to do the same as with using ExpectedException @Rule, but all the assertion should be written manually. However the advantage of this method is that you can use any custom assertion and any assertion library that you want:

    @Test
    public void testSomething(){
        try{
            sut.doSomething();
            fail("Expected exception");
        } catch(ExceptionType e) {
        //assert ExceptionType e
        } 
    }
    

提交回复
热议问题