Cdacians

Cdacians
Cdacians

Thursday 7 September 2017

Android Test tricks - Sharing code between UI & unit tests

Android Test tricks - Sharing code between UI & unit tests

In this series of posts I would like to share some useful tricks I learned over the last few years related to testing on Android.
The first trick will be really short

Sharing code between unit tests and integration tests

At the moment the most common Android testing layout includes 2 different test suites - unit tests (pure Java tests which run on JVM and don't require Android device) and integration (aka UI tests, aka Android tests, you name it) test suite which runs on Android device (or emulator).
Normally this looks something like this:
The problem is that sometimes you want to have code which is shared between those 2 source sets. Let's say some TestUtils.java which has some common functionality for both test suites.
Unfortunately, UI test suite and unit test suite do not share code, i.e. any code placed in test folder will not be visible by UI test suite (and vice versa).
But luckily there is an easy solution! Gradle magic to the rescue!

Creating a shared test folder

What we need to do - is create a new folder (let's call it testShared) inside app/srcfolder:
Now create our beloved TestUtils.java class:
And now goes the magic part. In your app/build.gradle file add the following (anywhere outside android closure):
android.sourceSets {  
    test {
        java.srcDirs += "$projectDir/src/testShared"
    }

    androidTest {
        java.srcDirs += "$projectDir/src/testShared"
    }
}
This way we just told both test suites to also include our testShared folder in their source sets.
Now after you sync your project with Gradle changes, you should be able to reference your TestUtils class from both UI and unit test suites:
Have fun!

No comments:

Post a Comment