Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.0k 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 Reply

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...