How to rotate activity, I mean: screen orientation change using Espresso?

FalconBot picture FalconBot · May 21, 2016 · Viewed 9.6k times · Source

I have decided that one of the testing criteria for my application tests with Google's Espresso is:

Test should maintain Activity state after screen orientation rotation

How do I rotate the screen when using Espresso?


I have tried the following Robotium code (Yes I placed Robotium code in my Espresso test so sue me)

solo.setActivityOrientation(solo.LANDSCAPE);
solo.setActivityOrientation(solo.PORTRAIT);

but It crashes the application when I run it within my Espresso test.
Is there any way to do this?

Thanks in advance for any help

Answer

Slava picture Slava · Mar 4, 2017

If you have the only Activity in your test case, you can do:

1. Declare you test Rule.

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

2. Get you Activity and apply a screen rotation.

mActivityTestRule.getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
mActivityTestRule.getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

That's a piece of pie!