问题
I have a test in Espresso that needs to assert that a certain action cause an exception to be thrown.
However it seems that the Espresso framework swallows the original exception and only surfaces a PerformException
.
回答1:
Eventually I found a way to do it. I've created a custom Hamcrest matcher that allows you to verify a nested exception.
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());
}
}
And then you can use it as follows in your test:
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() {
...
}
}
回答2:
You can do this
@Test( expected = ArrayIndexOutOfBoundsException.class) //OR any other
throwable
public void myTest() {
}
回答3:
Why not use this:
@Test(expected = PerformException::class)
fun traderSummaryContainer_notScroll() {
onView(withId(R.id.traderSummaryContainer))
.perform(scrollTo())
}
回答4:
Use normal try catch solved my problem, i know the exception is nested. But we can still check it by cause:
var error: Throwable? = null
try {
onView(something).perform(click())
} catch (e: Throwable) {
error = e;
}
assert(error!!.cause is MySpecificException)
assert(error!!.cause!!.message == "My specific error message")
I have tried the above custom Hamcrest matcher approach, but i ended up having flaky tests, so moved into this one eventually.
来源:https://stackoverflow.com/questions/50563600/assert-exceptions-in-android-espresso-test