Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

Junit5: Expect nested exception

How does JUnit 5 allow to check for a nested exception? I'm looking for something to what could be done in JUnit 4 with the help of a @org.junit.Rule, as shown in the following snippet:

class MyTest {

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

    @Test
    public void checkForNestedException() {

        // a JPA exception will be thrown, with a nested LazyInitializationException
        expectedException.expectCause(isA(LazyInitializationException.class));

        Sample s = sampleRepository.findOne(id);

        // not touching results triggers exception
        sampleRepository.delete(s);
    }
}

Edit as per comment:

In JUnit 5 Assertions.assertThrows(LazyInitializationException.class) does not work, since LazyInitializationException is the nested exception (cause) of JpaSystemException.

Only the check for the outer exception can be made, which is not as desired:

// assertThrows does not allow to check for nested LazyInitializationException
Assertions.assertThrows(JpaSystemException.class, () -> {

    Sample s = sampleRepository.getOne(id);

    // not touching results triggers exception
    sampleRepository.delete(s);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Thanks to johanneslink, the solution is actually simple:

// assertThrows returns the thrown exception (a JpaSystemException)
Exception e = Assertions.assertThrows(JpaSystemException.class, () -> {

    Sample s = sampleRepository.getOne(id);

    // not touching results triggers exception
    sampleRepository.delete(s);
});

// Now the cause of the thrown exception can be checked
assertTrue(e.getCause() instanceof LazyInitializationException);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...