В конце концов я нашел способ сделать это.Я создал собственный инструмент сопоставления Hamcrest, который позволяет вам проверять вложенное исключение.
public class NestedExceptionMatcher extends TypeSafeMatcher<Throwable> {
private final Class<?> mExpectedType;
private final Matcher<String> mMessageMatcher;
static NestedExceptionMatcher expectNestedThrowable(Class<?> expectedType, Matcher<String> messageMatcher) {
return new NestedExceptionMatcher(expectedType, messageMatcher);
}
NestedExceptionMatcher(Class<?> expectedType, Matcher<String> messageMatcher) {
mExpectedType = expectedType;
mMessageMatcher = messageMatcher;
}
@Override
protected boolean matchesSafely(Throwable item) {
boolean matches = isMatch(item);
Throwable currentThrowable = item.getCause();
while (!matches && currentThrowable != null) {
matches = isMatch(currentThrowable);
currentThrowable = currentThrowable.getCause();
}
return matches;
}
@Override
public void describeTo(Description description) {
description
.appendText("expects type ")
.appendValue(mExpectedType)
.appendText(" with a message ")
.appendDescriptionOf(mMessageMatcher);
}
private boolean isMatch(Throwable t) {
return t.getClass().isAssignableFrom(mExpectedType) && mMessageMatcher.matches(t.getMessage());
}
}
И затем вы можете использовать его в своем тесте следующим образом:
public class SomeActivityTest {
@Rule
public ActivityTestRule<SomeActivity> mRule = new ActivityTestRule<>(
SomeActivity.class, false, false);
@Rule
public ExpectedException mExceptionRule = ExpectedException.none();
@Test
public void testClick_whenInvalidParamsAreSet_shouldThrowException() {
mRule.launchActivity(getIntentWithInvalidParams());
mExceptionRule.expect(expectNestedThrowable(
IllegalArgumentException.class,
containsString("parameter isn't defined")
));
onView(withId(R.id.my_btn)).perform(click());
}
private Intent getIntentWithInvalidParams() {
...
}
}