verybadalloc
verybadalloc

Reputation: 5796

Share code between unit test and instrumentation tests when using kotlin

Similar question: Sharing code between Android Instrumentation Tests and Unit Tests in Android Studio

My setup is the following:

This sharing is defined in gradle as:

sourceSets {
    test.java.srcDirs += 'src/sharedTest/java'
    androidTest.java.srcDirs += 'src/sharedTest/java'
}

This allows any Java class in src/test or src/androidTest to access the utils. but not the Kotlin unit tests. My assumption is that they are not added to the sourceSets.

My question is: how can I add them? I tried:

sourceSets {
    test.kotlin.srcDirs += 'src/sharedTest/java'
}

But that doesn't seem to work.

Upvotes: 5

Views: 1136

Answers (2)

Andrzej Sawoniewicz
Andrzej Sawoniewicz

Reputation: 1681

If your project has both java and kotlin code the key is to have:

src/{folderName}/java

and

src/{folderName}/kotlin

Where {folderName} is: test, androidTest, sharedTest or whatever.

I use:

android {
    sourceSets {
        androidTest.java.srcDirs += "src/androidTest/kotlin"
        androidTest.java.srcDirs += "src/sharedTest/java"
        androidTest.java.srcDirs += "src/sharedTest/kotlin"
        test.java.srcDirs += "src/test/kotlin"
        test.java.srcDirs += "src/sharedTest/java"
        test.java.srcDirs += "src/sharedTest/kotlin"
    }
}

This is some inconsistency as you can have all java and kotlin code under the same:

main/java

directory.

Upvotes: 0

tynn
tynn

Reputation: 39843

The default setup would be making the Kotlin source sets visible to the Java compiler and the IDE as well:

android {
    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
        test.java.srcDirs += 'src/test/kotlin'
        test.java.srcDirs += 'src/sharedTest/java'
        androidTest.java.srcDirs += 'src/sharedTest/java'
    }
}

You don't need to configure the Kotlin source sets by itself.

Upvotes: 1

Related Questions