在集成测试的反射信息中不存在的测试中定义的 Kotlin 注释

标签 kotlin gradle

我们有一个相当标准的 Kotlin DSL Gradle 构建。我们添加了一个 integrationTest 源集和任务:

plugins {
    kotlin("jvm") version "1.3.72"
    application
}

sourceSets {
    create("integrationTest") {
        compileClasspath += sourceSets.main.get().output
        runtimeClasspath += sourceSets.main.get().output
        compileClasspath += sourceSets.test.get().output
        compileClasspath += sourceSets.main.get().runtimeClasspath
        runtimeClasspath += sourceSets.test.get().output
        resources.srcDir(sourceSets.test.get().resources.srcDirs)
    }
}

val integrationTest = task<Test>("integrationTest") {
    description = "Runs the integration tests."
    group = "verification"
    testClassesDirs = sourceSets["integrationTest"].output.classesDirs
    classpath = sourceSets["integrationTest"].runtimeClasspath
    mustRunAfter(tasks.test)
    useJUnitPlatform()
}
src/integrationTest/kotlin 中的类可以很好地使用 src/test/kotlin 中的类,但是 src/test/kotlin 中定义的注释不会显示在 src/integrationTest/kotlin 中的类的反射数据中。在 src/test/kotlin 中的类上使用时,注释会按预期出现在反射数据中。
注释非常简单:
@Target(FUNCTION, CLASS)
// NB: Default Retention is RUNTIME (Annotation is stored in binary output and visible for reflection)
annotation class SystemProperty(val key: String, val value: String)

// Kotlin does not yet support repeatable annotations https://youtrack.jetbrains.com/issue/KT-12794
@Target(FUNCTION, CLASS)
annotation class SystemProperties(vararg val systemProperties: SystemProperty)
这是在 JUnit 5 扩展中使用注释的方式:
class SystemPropertyExtension : BeforeAllCallback {
    override fun beforeAll(extensionContext: ExtensionContext) {
        val clazz = extensionContext.requiredTestClass
        clazz.getAnnotation(SystemProperty::class.java)?.let {
            System.setProperty(it.key, it.value)
        }
        clazz.getAnnotation(SystemProperties::class.java)?.let {
            it.systemProperties.forEach { prop -> System.setProperty(prop.key, prop.value) }
        }
    }
}
以及测试本身的典型用法:
@SystemProperty(key = "aws.s3.endpoint", value = "http://localstack:4566")
@ExtendWith(SystemPropertyExtension::class)
class SomeIntegrationTest {
    //
}
在运行测试时设置断点会显示 System.setProperty(it.key, it.value) 被调用。但是,在调试集成测试时,没有命中断点。
关于这里可能有什么问题/遗漏的任何想法?
我们可以在项目中添加一个“测试”模块并导出 test-jar,但如果可能的话希望避免这种情况。

最佳答案

注释只是缺少@Inherited。它们是在类中找到的,但没有@Inherited,它们不是通过父类(super class)找到的。

关于在集成测试的反射信息中不存在的测试中定义的 Kotlin 注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62899692/

相关文章:

android - 使用 PowerMockRunner 测试 LiveData

android - RecyclerView.OnItemClickListener 与在 RecyclerView 的查看器中实现 onClickListener?

Gradle - 帮助为 Ivy Publish 动态设置修订

java - 如何在没有gradle或Maven或Eclipse的情况下将jar文件添加到java项目中

gradle - 如何将默认 jvm args 设置为 gradle 应用程序插件?

android - @InstallIn,只能和@DefineComponent注解的类一起使用,但是发现: [com. abc.xyz.AppClass]

reflection - Kotlin 对对象实例的反射

gradle - 使用 Kotlin 实现插件时如何为 Gradle 扩展任务?

android - fragment 上的 constraintLayout 关键帧动画

eclipse - “gradlew eclipse”命令不起作用