Home > AI > Backend > SpringBoot > Junit >

Test error thrown

Method 1: validate error type and error message.

Disadvantage: not so straightforward and elegant

@Test
public void whenExceptionThrown_thenAssertionSucceeds() {
    // 1 test error type  
    Exception exception = assertThrows(NumberFormatException.class, () -> {
        Integer.parseInt("1a");
    });


    // 2 test error message
    String expectedMessage = "For input string";
    String actualMessage = exception.getMessage();
    assertTrue(actualMessage.contains(expectedMessage));
}

Method 2: only care error type

Disadvantage: cannot validate error message

@Test(expected = IllegalArgumentException.class)
    public void whenExceptionThrown_thenExpectationSatisfied() {
        mnUserDao.save(null);
    }

Method 3: most elegant

@Rule
    public ExpectedException exceptionRule = ExpectedException.none();

    @Test
    public void whenExceptionThrown_thenRuleIsApplied() {
        exceptionRule.expect(IllegalArgumentException.class);
        exceptionRule.expectMessage("Object to save must not be null!");
        mnUserDao.save(null);
    }

Leave a Reply