First I added the following UI Automator to my app:
1 |
androidTestImplementation 'com.android.support.test.uiautomator:uiautomator-v18:2.1.3' |
So now my build.gradle (Module) file has the following dependecies:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
dependencies { implementation 'androidx.core:core-ktx:1.7.0' implementation 'androidx.appcompat:appcompat:1.5.1' implementation 'com.google.android.material:material:1.6.1' implementation 'androidx.constraintlayout:constraintlayout:2.1.4' implementation 'net.objecthunter:exp4j:0.4.8' testImplementation 'junit:junit:4.13.2' androidTestImplementation 'androidx.test.ext:junit:1.1.3' androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0' androidTestImplementation 'com.android.support.test.uiautomator:uiautomator-v18:2.1.3' } |
Then under the package app/src/androidTest/java/net/catzie/samplecalculatorapp I added the following instrumented test class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
package net.catzie.samplecalculatorapp import android.support.test.uiautomator.UiDevice import androidx.test.espresso.Espresso import androidx.test.espresso.ViewInteraction import androidx.test.espresso.action.ViewActions import androidx.test.espresso.matcher.ViewMatchers import androidx.test.ext.junit.rules.ActivityScenarioRule import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry.getInstrumentation import org.junit.Assert.* import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ValueRetainedInstrumentedTest { @get:Rule var activityRule: ActivityScenarioRule<MainActivity> = ActivityScenarioRule(MainActivity::class.java) @Test fun test_ui_value_after_screen_rotation() { Espresso.onView(ViewMatchers.withId(R.id.num_1)).perform(ViewActions.click()) Espresso.onView(ViewMatchers.withId(R.id.num_period)).perform(ViewActions.click()) Espresso.onView(ViewMatchers.withId(R.id.num_5)).perform(ViewActions.click()) val device = UiDevice.getInstance(getInstrumentation()) device.setOrientationLeft() val displayPanel: ViewInteraction = Espresso.onView(ViewMatchers.withId(R.id.display_panel)) val displayPanelText = InstrumentedTestHelper.getText(displayPanel) assertEquals("1.5", displayPanelText) } } |
What it does is press the buttons 1, period, and 5 on the calculator’s UI to show “1.5” which should show up the display panel, rotate the screen of the emulator/device, and then check if the display panel is still showing the value “1.5”.
I use a ViewModel and LiveData to let the value survive configuration changes such as screen rotation.