Use Kotlin compiler options for test sources in Android Studio
Asked Answered
D

1

6

In my test sources I want to use some experimental Kotlin compiler feature to not see the lint warnings and errors for them in Android Studio. For example, I want to apply the following Kotlin options to all test sources.

compileTestKotlin {
  kotlinOptions {
    freeCompilerArgs += [
        '-Xopt-in=kotlin.time.ExperimentalTime',
        '-Xopt-in=kotlinx.coroutines.ExperimentalCoroutinesApi',
    ]
  }
}

(source)

Out of the box this doesn't work in an Android project, because there is no compileTestKotlin method. According to the kotlin-android Gradle plugin docs, it should be possible to do this for compileVariantNameKotlin in an afterEvaluate block, e.g.:

afterEvaluate {
  compileDebugUnitTestKotlin {
    kotlinOptions {
      freeCompilerArgs += [
        '-Xopt-in=kotlin.time.ExperimentalTime',
        '-Xopt-in=kotlinx.coroutines.ExperimentalCoroutinesApi',
      ]
    }
  }
}

(and similar for compileReleaseUnitTestKotlin)

Although this works (builds and test run and pass just fine), there seems to be no effect in Android Studio: usages of the experimental compiler features are still marked with warnings/errors.

How do I enable these compiler features for my test sources in such a way that AS recognizes and uses them?

Desertion answered 5/11, 2020 at 15:19 Comment(1)
I wonder: is this simply an Android Studio feature that is unavailable, being developed, or bugged? If so, is there some issue somewhere that I can follow or contribute my use case to, if unknown (I can hardly imagine)?Desertion
R
9

This worked for me on Android Studio 4.2.2, AGP version 4.2.0, Kotlin version 1.5.10:

android {
    testOptions {
        kotlinOptions {
            freeCompilerArgs += [
                '-Xopt-in=kotlin.time.ExperimentalTime',
                '-Xopt-in=kotlinx.coroutines.ExperimentalCoroutinesApi',
            ]
        }
    }
}
Roselynroseman answered 12/7, 2021 at 20:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.