Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you force an orientation change in an Android Instrumentation test?

I'm writing some acceptance tests for an application using the ActivityInstrumentationTestCase2 class. I want to cause an orientation change from within the test to ensure that a number of things happen. Among these things are ensuring that Activity state is preserved, but also I'd like to ensure that the appropriate layout for the orientation is used.

I know I can simply test the onSaveInstanceState/onRestoreInstanceState/onPause/onResume/etc. methods to make sure instance state is preserved. However, I was wondering if there is actually a mechanism for causing an orientation change event?

Would this involve injecting some kind of motion event to trick the device/emulator into thinking that it has been rotated, or is there an actual method for this provided by the Instrumentation?

Thanks & Cheers!

like image 854
plainjimbo Avatar asked Aug 18 '10 19:08

plainjimbo


People also ask

How do you change orientation when retaining data?

Another most common solution to dealing with orientation changes by setting the android:configChanges flag on your Activity in AndroidManifest. xml. Using this attribute your Activities won't be recreated and all your views and data will still be there after orientation change.

How can we detect the orientation of the screen in Android?

int orientation = display. getOrientation(); Check orientation as your way and use this to change orientation: setRequestedOrientation (ActivityInfo.


2 Answers

You do not actually have to use Robotium for this at all. In fact, if you view the source of Robotium all it is doing when you call

solo.setActivityOrientation(Solo.LANDSCAPE); 

is

myActivity = this.getActivity(); // In your setUp method()  ...  myActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); 
like image 96
AndrewKS Avatar answered Oct 24 '22 01:10

AndrewKS


As AndrewKS wrote you can use

getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); assertTrue(...); 

to request an orientation change. But the rotation itself is executed asynchronous. To really test the state after the orientation change you need to wait a short time after the request:

getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); Thread.sleep(50); // depends on performance of the testing device/emulator assertTrue(...); 
like image 32
Rodja Avatar answered Oct 24 '22 02:10

Rodja