Junit 验证exception的几种方法

  1. try - catch

    @Test
    public void testInvalidData() {
        prepareTestData();
    
        try {
            userService.fetchUser(1234);
            Assert.fail("IllegalArgumentException not thrown");
        } catch (IllegalArgumentException expected) {
        }
    }
  2. Annotation Attribute

    @Test(expected = IllegalArgumentException.class)
    public void testInvalidData() {
        prepareTestData();
    
        // should throw IllegalArgumentException
        userService.fetchUser(1234);
    }

    Junit5 以后不再有这个feature

  3. Rule ExpectedException

    @Rule
    public ExpectedException thrown = ExpectedException.none();
    
    @Test
    public void testInvalidData() {
        prepareTestData();
    
        thrown.expect(IllegalArgumentException.class);
        userService.fetchUser(1234);
    }

    JUnit 4 contains the built-in rule ExpectedException. (please remember that JUnit 5 uses extensions instead of rules).

    This approach is similar to try-catch and @Test(expected = ...), but we can control from which point the exception is expected.

  4. assertThrows

    @Test
    public void testInvalidData() {
        prepareTestData();
    
        Assertions.assertThrows(IllegalArgumentException.class, () -> {
            userService.fetchUser(1234);
        });
    }

    Assertions.assertThrows also returns the exception object to execute further asserts, e.g. to assert the message. 

 

Summary

I try to use assertThrows as often as possible because the test code gets both readable and flexible. But all the other mentioned approaches are also valid if correctly used.

你可能感兴趣的:(Java,basic)