Mr T
Mr T

Reputation: 81

Espresso Test for Activity with Forced Portrait Mode Fails Orientation Assertion

I am testing an Android app using Espresso, and I have an activity that should only be displayed in portrait mode. To enforce this, I programmatically lock the activity in portrait mode when it is started. This works correctly in the app during normal usage.

However, when testing this behavior with Espresso, I encounter an issue. In my test, I simulate a rotation using the following code:

val device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())
device.setOrientationRight()

This successfully rotates the device to landscape. Then, I navigate to the activity that locked to portrait mode. The activity appears correctly in portrait mode as expected.

To verify the orientation in my test, I use this code:

val context = ApplicationProvider.getApplicationContext<Context>()
val orientation = context.resources.configuration.orientation
assertEquals(Configuration.ORIENTATION_PORTRAIT, orientation)

However, the test fails because the orientation returned is Configuration.ORIENTATION_LANDSCAPE, even though the activity is displaying the portrait layout correctly.

It seems the device’s orientation remains in landscape, and the system-level configuration is not updated to reflect the forced portrait mode of the activity. Since there is only one layout file (portrait), I cannot verify the orientation by checking which layout is displayed.

How can I test this behavior correctly? Is there a way to assert that the activity is truly locked in portrait mode even though the device’s orientation has been changed?

Upvotes: 0

Views: 26

Answers (1)

Mr T
Mr T

Reputation: 81

As mentioned in the comment, the test works when using the Activity context and checking the orientation.

    val orientation = activity.resources.configuration.orientation

Upvotes: 0

Related Questions