5

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

My setup is the following:

  • src/test folder that contains unit tests. These can be either Java or Kotlin classes
  • src/androidTest that contains instrumentation tests. These can also be either Java or Kotlin classes
  • src/sharedTest is a folder that contains a bunch of utils that are shared between unit and instrumentation tests.

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.

tynn
  • 38,113
  • 8
  • 108
  • 143
verybadalloc
  • 5,768
  • 2
  • 33
  • 49

2 Answers2

1

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.

tynn
  • 38,113
  • 8
  • 108
  • 143
  • Pretty sure this won't work. I don't have `src/main/kotlin` nor `src/test/kotlin`. What I need is for Kotlin unit tests (who are in `src/test/java`, not `src/test/kotlin`) to be able to access Java clases. Unless you are suggesting that I should move said Kotlin unit tests to `src/test/kotlin`... – verybadalloc Jun 14 '17 at 13:16
  • Yes, you should have a different source set for Kotlin. I tried this setup and didn't have any issues. But if you have the Kotlin sources in the Java source set alread, it should have the same effect using the last two lines... – tynn Jun 14 '17 at 13:18
  • Alright, I will give it a try, and report back. Thanks! – verybadalloc Jun 14 '17 at 13:24
0

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.

Andrzej Sawoniewicz
  • 1,541
  • 2
  • 16
  • 18