Guiding Through Activity Screen Orientation Changes in Espresso Tests

Guiding Through Activity Screen Orientation Changes in Espresso Tests

11 April 2024 Stephan Petzl Leave a comment Tech-Help

Ensuring that your Android application maintains its state after screen orientation changes is a crucial part of testing. When automating tests with Espresso, you may find yourself needing to programmatically rotate the screen to assess this behavior. This guide will walk you through the process of changing the screen orientation within your Espresso tests.

Using ActivityTestRule to Change Orientation

The most straightforward way to change the orientation of your screen during testing is by using the ActivityTestRule class. Here’s how you can achieve this:

  1. Declare your test rule with the activity you wish to test:

    @Rule
    public ActivityTestRule<TestActivity> mActivityTestRule = new ActivityTestRule<>(TestActivity.class);
                
  2. Get your activity and apply a screen rotation:

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

This method is simple and allows you to rotate the screen between landscape and portrait orientations.

Integrating UIAutomator for Screen Rotation

If you prefer using UIAutomator, you can incorporate it into your Espresso tests to manage screen orientations. To do this, follow these steps:

  1. Add the UIAutomator library to your dependencies:

    dependencies {
      androidTestImplementation 'androidx.test.uiautomator:uiautomator:2.2.0'
    }
                
  2. Create a new AndroidManifest.xml in the androidTest folder if your app’s minimum SDK version is below 18:

    <?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>
                
  3. In your test, use the following code to rotate the screen:

    UiDevice device = UiDevice.getInstance(getInstrumentation());
    
    device.setOrientationLeft();
    device.setOrientationNatural();
    device.setOrientationRight();
                

Note that UIAutomator requires a minimum SDK version of 18, so ensure that your testing environment meets this requirement.

Conclusion

Screen orientation change is a common requirement in application testing, and Espresso provides you with the tools to handle this scenario. By using either the ActivityTestRule or UIAutomator, you can simulate orientation changes and verify that your application behaves as expected. Implement these methods in your Espresso tests to ensure your app’s resilience against orientation changes.

Like this article? there’s more where that came from!