4

Is there a way to manually fail an Espresso test?

Say I want to compare the values of two int types and fail the test if they don't match:

@Test
public void testTwoInts() {

    int var1 = mActivityTestRule.getActivity().var1;
    int var1 = mActivityTestRule.getActivity().var2;

    if(var1 != var2)
        fail();
}

1 Answer 1

9

Espresso is built on JUnit, so you can use JUnit assertions with it. This makes it much clearer what you are intending to do. In this case, do import static org.junit.Assert.assertTrue and then in your test, do

@Test
public void testTwoInts() {

    int var1 = mActivityTestRule.getActivity().var1;
    int var1 = mActivityTestRule.getActivity().var2;

    assertEquals(var1,var2);
}

If you really want to do it manually (not recommended), JUnit provides a fail method in that same class. Do import static org.junit.Assert.fail and then use either version of the fail method (one takes no arguments, and one takes a string explaining the reason for the failure). Here you could do

@Test
public void testTwoInts() {

    int var1 = mActivityTestRule.getActivity().var1;
    int var1 = mActivityTestRule.getActivity().var2;

    if(var1 != var2)
        fail("The integers are not equal");
}
7
  • Great thanks, I guess JUnit is typically used with the Java SDK where Expresso is used for Android and offers only view assertions?
    – the_prole
    Sep 3, 2017 at 22:34
  • I'm not sure quite what you are asking. Testing on Android uses JUnit, even if you only import the Espresso classes (I bet your class is annotated with @RunWith(AndroidJUnit4.class)?). Espresso just adds a lot of assertions, rules, and other JUnit toys for working with views and such. Everything with JUnit is available to you (including Hamcrest matchers if you need more complicated assertions - in fact, that is what alot of Espresso is). I don't think the Espresso docs explain this clearly enough.
    – Matthew
    Sep 3, 2017 at 22:41
  • I see, so Espresso is built on top of JUnit. The only annotations (in my test class) are @Rule and @Test.
    – the_prole
    Sep 3, 2017 at 22:47
  • Hmmm... Maybe I've been using an unnecessary annotation. Even so, yes Espresso is built on top of JUnit, so it has the full power of JUnit, plus all the extra stuff for interacting with views, activities, and so on. Did you have to specify the runner (android.support.test.runner.AndroidJUnitRunner) in your build file? If you look at the setup instructions for espresso, you can see references to JUnit in several places.
    – Matthew
    Sep 3, 2017 at 23:02
  • Yeah, that property is declared in my defaultConfig block testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    – the_prole
    Sep 3, 2017 at 23:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.