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?
The Android Plugin for Gradle compiles the local unit test code located in the src/test/java/
only by default. So you need to define a run configuration for your sharedTest folder as described below.
That's all, now click 'apply' and 'ok'. then choose that configuration from the drop down menu near the run button and click run.
Note: You can create any number of configurations and switch between them easily using the drop down menu left to the green triangle shaped run button.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With