Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Access Activity from ActivityScenarioRule

I am using ActivityScenarioRule for Espresso UI Testing and I wanted to get access to the method getStringArray(), calling which requires the Activity . So, is there any way to retrieve the Activity by the ActivityScenarioRule , maybe something similar to getActivity in ActivityTestRule.

@Rule
    public ActivityScenarioRule activityScenarioRule = new ActivityScenarioRule<>(MainActivity.class);

I am not using ActivityTestRule, because it is deprecated!

like image 523
Satyam Bansal Avatar asked May 22 '20 10:05

Satyam Bansal


People also ask

How do you get activity from Activityscenariorule?

You can access the ActivityScenario instance via getScenario() . You may finish your activity manually in your test, it will not cause any problems and this rule does nothing after the test in such cases. This rule is an upgraded version of the now deprecated ActivityTestRule .

What is an activity scenario?

ActivityScenario provides APIs to start and drive an Activity's lifecycle state for testing. It works with arbitrary activities and works consistently across different versions of the Android framework. The ActivityScenario API uses Lifecycle.

What is activity test rule?

This rule provides functional testing of a single Activity .


1 Answers

Espresso states the following:

At the same time, the framework prevents direct access to activities and views of the application because holding on to these objects and operating on them off the UI thread is a major source of test flakiness.

When there is no other way I use the following method to get an arbitrary activity from an ActivityScenarioRule. It uses onActivity mentioned in the accepted answer:

private <T extends Activity> T getActivity(ActivityScenarioRule<T> activityScenarioRule) {
        AtomicReference<T> activityRef = new AtomicReference<>();
        activityScenarioRule.getScenario().onActivity(activityRef::set);
        return activityRef.get();
    }

Any onView(...) code inside onActivity led to a timeout in my testcases. So, I extracted the activity and used it with success outside the onActivity. Beware tho! See the statement above.

like image 139
tim.k Avatar answered Oct 13 '22 00:10

tim.k