Search code examples
androidjunitjunit4functional-testingandroid-espresso

Assume view state with Espresso test


JUnit library has an Assume.* instructions like Assume.assumeTrue(boolean) which works like assertions, but not cause test to fail and just to been ignored.

I want to perform such checking in arrange part of test for one of my views, by example assume, that founded checkbox is checked before starting the act part of test.

Take a look:

@Rule
public ActivityTestRule<MainActivity> mActivityTestRule = new ActivityTestRule<>(MainActivity.class);

@Test
public void deselectFilter_AllFiltersSelected_CheckboxAllSelectedUnchecked() {
    //arrange
    ViewInteraction checkBox = onView(
            allOf(withId(R.id.cbCheckAll), isDisplayed()));

    //assume that this checkbox is checked 

    //act
    ...
    //assert
    ...
}

In the arrange part i've received not a View, but ViewInteraction. So I can perform such assertion like checkBox.check(matches(isChecked()))
But how to perform assume?


Solution

  • You could write a custom ViewAssertion to assume that no Exception is thrown when Espresso ViewMatcher fails:

    public static ViewAssertion assume(final Matcher<? super View> viewMatcher) {
        return new ViewAssertion() {
            @Override
            public void check(final View view, final NoMatchingViewException noViewFoundException) {
                try {
                    ViewAssertions.matches(viewMatcher).check(view, noViewFoundException);
                } catch (Throwable e) {
                    // Assume that there is no exception
                    Assume.assumeNoException(e);
                }
            }
        };
    }
    

    Then you can use that assertion to assume like:

    onView(withId(R.id.cbCheckAll)).check(assume(isChecked()));