Who else wanted to share some code between test and androidTest?

There are two types of tests you can have on Android, JUnit tests and instrumented tests. They both have different aims and they deserve a blog post (or perhaps several) to cover their use cases.

But to keep it short, JUnit tests are simple and aim to isolate a component, i.e. a class, and test all his methods. In the case of Android, JUnit tests are located on the test folder under your project source, and they shouldn't cover anything that has to do with the Android SDK, thus pure Kotlin or Java code.

Instrumented tests on the other hand cover more complex flows which include the Android SDK, testing of views and so on. They are located on the folder androidTest.

There are multiple tools and frameworks that make easier to code those tests such as Mockito, Espresso, Roboelectric, and Selenium, which I will cover in future posts.

Sharing code between test types

It's very common to have some collection of methods or variables used for testing, and more often than not we land in a situation where we want to share it between our JUnit tests and instrumented tests.

Not sharing the code would imply duplication, which violates the DRY principle. We don't want that.

So, there's a little trick you can do with Gradle 😃. On the app's build.gradle file, add the following:

	sourceSets {
        test {
            java.srcDirs += "$projectDir/src/testShared"

        androidTest {
            java.srcDirs += "$projectDir/src/testShared"

What you are doing here is to tell Gradle to include whatever you place under the folder src/testShared into both your test and androidTest folders. So create the given folder and place the code you want to share between them in there!

Extra: Sharing variables

If you want to share variables, another way to do it is by defining them directly into your build.gradle file:

android {
    defaultConfig {
        buildConfigField("String", "MY_VAR", "\"value\"")

Then, you can access MY_VAR as BuildConfig.MY_VAR everywhere in your app, including tests.

Probably there are other ways to do this with Gradle, if you know any other don't hesitate to leave a comment below!