5

I am trying to test my application with the Espresso framework. It should be tested whether the application is exited when pressing back in the main activity and whether the main application is displayed when calling another activity from the main activity and then pressing back.

public class MainActivityTest {
    @Rule
    public IntentsTestRule<MainActivity> intentsTestRule = new IntentsTestRule<>(
            MainActivity.class
    );

    @Test
    public void test_pressBack() {
        try {
            pressBack();
            fail();
        } catch (NoActivityResumedException exc) {
            // test successful
        }
    }

    @Test
    public void test_anotherActivity_pressBack() {
        onView(withId(R.id.button1)).perform(click());
        pressBack();
        intended(hasComponent(new ComponentName(getTargetContext(), MainActivity.class)));
    }
}

For the first scenario (exit app), I am catching NoActivityResumedException, but this does not seem like the right way to do this.

For the second scenario (return to main activity), I get an intent error:

android.support.test.espresso.base.DefaultFailureHandler$AssertionFailedWithCauseError: Wanted to match 1 intents. Actually matched 0 intents.

IntentMatcher: has component: has component with: class name: is "myPackage.MainActivity" package name: an instance of java.lang.String short class name: an instance of java.lang.String

Matched intents:[]

Recorded intents:
-Intent { cmp=myPackage/.AnotherActivity} handling packages:[[myPackage]])
epR8GaYuh
  • 311
  • 9
  • 21
  • So what's the question? And you haven't provided your code for the 2nd test – Shurov Feb 03 '19 at 13:06
  • @Shurov The question is how the two tests should look like, especially as the second test case is throwing an exception. And the code for the second test is already given with the second method - named `test_anotherActivity_pressBack` - annotated as test case. – epR8GaYuh Feb 03 '19 at 13:46
  • sorry, my fault. I've added an answer below – Shurov Feb 03 '19 at 14:41

1 Answers1

2

Regarding 1st test - you may use

Espresso.pressBackUnconditionally()

that is not throwing NoActivityResumedException exception. Afterwards check if your activity is running/in foreground.

Regarding 2nd test:

intended(hasComponent(MainActivity::class.qualifiedName))

works for me (code in Kotlin). So, basically using hasComponent(String className) instead of hasComponent(ComponentName componentName)

Shurov
  • 400
  • 1
  • 9
  • 20
  • While the first test works, the second one is still showing the same error when using `intended(hasComponent(MainActivity.class.getName()));` after `pressBack()`. – epR8GaYuh Feb 03 '19 at 19:36