public class ExceptionMatcher extends org.hamcrest.TypeSafeDiagnosingMatcher<Runnable>
For example:
assertThat(() -> obj.doStuff("p1"),
throwsException(NullPointerException.class));
Exception details, such as message and cause, can also be evaluated using additional methods. For example:
assertThat(() -> obj.doStuff("p1"),
throwsException(IllegalStateException.class)
.withCause(FileNotFoundException.class));
assertThat(() -> obj.doStuff(null),
throwsException(MyException.class)
.withMessageContaining("ERR-12008"));
| Modifier and Type | Method and Description |
|---|---|
void |
describeTo(org.hamcrest.Description description)
Describes the "expected" pat of the test description.
|
static ExceptionMatcher |
throwsException(Class<? extends Exception> exception)
Creates a matcher that matches if the examined procedure throws a given exception.
|
ExceptionMatcher |
withCause(Class<? extends Throwable> cause)
Assigns an expected cause for evaluation.
|
ExceptionMatcher |
withMessageContaining(String... substrings)
Assigns one or more expected substrings for the exception message evaluation.
|
public static ExceptionMatcher throwsException(Class<? extends Exception> exception)
For example:
assertThat(() -> obj.doStuff("p1"),
throwsException(IllegalStateException.class));
exception - the exception to be checkedpublic ExceptionMatcher withCause(Class<? extends Throwable> cause)
For example:
assertThat(() -> obj.doStuff("p1"),
throwsException(IllegalStateException.class)
.withCause(FileNotFoundException.class));
cause - the cause to be checkedpublic ExceptionMatcher withMessageContaining(String... substrings)
For example:
assertThat(() -> obj.doStuff(null),
throwsException(IllegalArgumentException.class)
.withMessageContaining("argument cannot be null");
assertThat(() -> obj.doStuff(null),
throwsException(MyException.class)
.withMessageContaining("ERR-12008", "mandatory");
substrings - a substring of the exception message to be checkedpublic void describeTo(org.hamcrest.Description description)
SelfDescribing.describeTo(Description)Copyright © 2020. All rights reserved.