public class ExpectedExceptionExtension extends Object implements org.junit.jupiter.api.extension.TestExecutionExceptionHandler, org.junit.jupiter.api.extension.AfterTestExecutionCallback
ExpectedException annotation to a test method.
Usage example:
public class MyTest {
@Test
@ExpectedException(type = Exception.class, messageIs = "Boom!")
public void canHandleAnException() throws Exception {
// ...
throw new Exception("Boom!");
}
@Test
@ExpectedException(type = RuntimeException.class, messageStartsWith = "Bye")
public void canHandleAnExceptionWithAMessageWhichStartsWith() {
// ...
throw new RuntimeException("Bye bye");
}
}
Notes:
@Test
@ExpectedException(type = Throwable.class)
public void failsTestForMissingException() {}
This is to avoid a false positive where a test is declared to expect an exception and
passes even if no exception is thrown.
@Test
@ExpectedException(type = Throwable.class, messageIs = "Boom!")
public void canHandleAThrowable() throws Throwable {
throw new Exception("Boom!");
}
This is for consistency with JUnit Jupiter, in which AssertThrows matches an
exception type or any subclass of that exception type.
| Constructor and Description |
|---|
ExpectedExceptionExtension() |
| Modifier and Type | Method and Description |
|---|---|
void |
afterTestExecution(org.junit.jupiter.api.extension.ExtensionContext extensionContext)
The presence of
ExpectedException on a test is a clear statement by the developer that
some exception must be thrown by that test. |
void |
handleTestExecutionException(org.junit.jupiter.api.extension.ExtensionContext extensionContext,
Throwable throwable)
Handle the supplied
Throwable throwable. |
public void handleTestExecutionException(org.junit.jupiter.api.extension.ExtensionContext extensionContext,
Throwable throwable)
throws Throwable
Throwable throwable. If the extensionContext is annotated
with ExpectedException and if the throwable matches the expectations expressed
in the ExpectedException annotation then the supplied throwable is swallowed
otherwise the supplied throwable is rethrown.handleTestExecutionException in interface org.junit.jupiter.api.extension.TestExecutionExceptionHandlerextensionContext - the current extension contextthrowable - the Throwable to handleThrowablepublic void afterTestExecution(org.junit.jupiter.api.extension.ExtensionContext extensionContext)
throws Exception
ExpectedException on a test is a clear statement by the developer that
some exception must be thrown by that test. Therefore, if the invocation arrives here without
having been evaluated by handleTestExecutionException(ExtensionContext, Throwable) and
with no exception in the context then this expectation has not been met and rather than failing
silently (and giving a false positive) the library will explicitly fail on this condition.afterTestExecution in interface org.junit.jupiter.api.extension.AfterTestExecutionCallbackextensionContext - ExceptionCopyright © 2018. All rights reserved.