Joshua Augustinus
Joshua Augustinus

Reputation: 1670

How do I get Activity within an espresso test?

Im trying to use firebase ScreenShotter which takes the form:

ScreenShotter.takeScreenshot("main_screen_2", this /* activity */);

I'm not exactly sure how I'm supposed to get the Activity from within an Espresso test. At the moment my test class looks something like:

@RunWith(AndroidJUnit4.class)
@LargeTest
public class OtherTests {
    @Rule
    // Replace 'MainActivity' with the value of android:name entry in
    // <activity> in AndroidManifest.xml
    public ActivityScenarioRule <MainActivity> mActivityRule = new ActivityScenarioRule<>(MainActivity.class);




    @Test
    public void getDeviceInfo() {

        try {
            Thread.sleep(7000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


        TestHelper.tap("APP_HEADER");
        TestHelper.expect("TRUE_HOME_BUTTON",5000);
        ScreenShotter.takeScreenshot("main_screen_2", this /* activity */);
    }


}

Upvotes: 2

Views: 3010

Answers (2)

yogurtearl
yogurtearl

Reputation: 3065

You have to get the scenario and then run your code in the callback passed to onActivity

    @Test
    public void getDeviceInfo() {
        ...
        mActivityRule.getScenario()
             .onActivity(activity -> ScreenShotter.takeScreenshot("main_screen_2", activity));
         
    }

Upvotes: 2

fernandospr
fernandospr

Reputation: 3051

According to the sample app provided by Google (at the bottom), you can inherit from ActivityInstrumentationTestCase2 and use the getActivity() method.

However, as explained here, that class is deprecated in favor of ActivityTestRule which also has the getActivity() method.

public void testExample() {
    // Take a screenshot when app becomes visible.
    onView(isRoot());
    ScreenShotter.takeScreenshot("main_screen_1", getActivity());
}

Upvotes: 1

Related Questions