Java Magazine, Nov/Dec 2016
ORACLE COM JAVAMAGAZINE NOVEMBER DECEMBER 2016 33 junit 5 the extension is not in charge of that exception 2 After the test is executed check whether the expected exception was thrown If so do nothing because everything went as planned otherwise fail the test For this logic I need to interact with two extension points TestExecutionExceptionHandler and AfterTest ExecutionCallback so I implement the corresponding interfaces public class ExpectedExceptionExtension implements TestExecutionExceptionHandler AfterTestExecutionCallback @ Override public void handleTestExecutionException TestExtensionContext context Throwable throwable throws Throwable @ Override public void afterTestExecution TestExtensionContext context Lets start with step 1 and check whether the exception is the one expected For this I use a small utility function expectedException which accesses the @ Test annotation extracts the expected exception class and returns it in an Optional because maybe no exception was expected To capture the observed behavior I create an enum EXCEPTION and to persist the observation in the store I write store ExceptionStatus With these helpers in place I can implement the first extension point @ Override public void handleTestExecutionException TestExtensionContext context Throwable throwable throws Throwable boolean throwableMatchesExpectedException expectedException context filter expected expected isInstance throwable isPresent if throwableMatchesExpectedException storeExceptionStatus context EXCEPTION WAS_ THROWN_ AS_ EXPECTED else storeExceptionStatus context EXCEPTION WAS_ THROWN_ NOT_ AS_ EXPECTED throw throwable Note that by not rethrowing the exception I inform JUnit that I processed it and that all is in order Accordingly JUnit will neither call additional exception handlers with it nor fail the test So far so good Now after the test I need to check what happened so I can react accordingly Another helper loadExceptionStatus will retrieve the state and do me a further small favor when no exception was thrown the extension point I implemented above will not have been called which means no EXCEPTION instance was placed into the store In this case loadException Status will return EXCEPTION WAS_ NOT_ THROWN Here is the implementation @ Override public void afterTestExecution TestExtensionContext context switch loadExceptionStatus context case WAS_ NOT_ THROWN expectedException context
You must have JavaScript enabled to view digital editions.