Recently I show one of the google IO video about androidX testing which quote "Write Once, Run EveryWhere". Which makes me exciting to learn about androidX testing library.
And what I found that After long time google come up with the nice single library for Unit test and Instrumentation test for on/off devices. But I found some difficulties to run the same test on/off devices.
Basically In Android, We create two source root test/java
and androidTest/java
in which we store Unit test and Instrumentation test respectively. Unit test runs on JVM and Instrumentation run on device/simulation.
Then I wrote test for one of the fragment inside test/java
directory.
@RunWith(AndroidJUnit4::class)
class MyFragmenTest {
lateinit var scenario: FragmentScenario<MyFragment>
@Before
fun setUp() {
scenario = launchFragmentInContainer<MyFragment>()
}
@Test
fun `sample test`() {
scenario.onFragment {
// something
}
// some assertion
}
}
So When I execute this test using small green run icon, it run this test in JVM without emulator which is great. But to run the same test on device I have to move this code androidTest/java
source root.
Basically I got that same test can run everywhere you don't have to rely on different tool & library for the same work when we use androidX testing library.
What I tried.
After, Searching on google I found that we have to create the sharedTest/java
source root using below gradle line so that it can run both on or off device.
android {
...
sourceSets {
androidTest {
java.srcDirs += "src/sharedTest/java"
}
test {
java.srcDirs += "src/sharedTest/java"
}
}
}
After placing my code into sharedTest/java
and if I execute test using green run icon it always ask for device. Which is also confusing because I can never run this on JVM.
Here comes my question.
How to execute same test seamlessly on/off device without moving code to different source root?