Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 656
FalconBot Avatar asked May 21 '16 11:05

FalconBot


People also ask

What happens to an activity when the screen orientation changes?

When you rotate your device and the screen changes orientation, Android usually destroys your application's existing Activities and Fragments and recreates them. Android does this so that your application can reload resources based on the new configuration.

How do I adjust screen orientation?

Select the Start button, then type settings. Select Settings > System > Display, and choose a screen orientation from the drop-down list next to Display orientation.

How do I change the orientation of my activity on Android?

If you want to manually handle orientation changes in your app you must declare the "orientation" , "screenSize" , and "screenLayout" values in the android:configChanges attributes. You can declare multiple configuration values in the attribute by separating them with a pipe | character.


2 Answers

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!

like image 142
Slava Avatar answered Sep 21 '22 09:09

Slava


You can do it with uiautomator library

dependencies {   androidTestImplementation 'androidx.test.uiautomator:uiautomator:2.2.0'  } 

ui automator require min sdk version 18 so if your app has a lower min sdk you need to create a new AndroidManifest.xml in androidTest folder

<?xml version="1.0" encoding="utf-8"?> <manifest     xmlns:tools="http://schemas.android.com/tools"     package="your.package.name">     <uses-sdk tools:overrideLibrary="android.support.test.uiautomator.v18"/> </manifest> 

and then in your test

UiDevice device = UiDevice.getInstance(getInstrumentation());  device.setOrientationLeft(); device.setOrientationNatural(); device.setOrientationRight(); 
like image 23
lelloman Avatar answered Sep 23 '22 09:09

lelloman