我们有一个相当标准的 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/