【发布时间】:2022-06-21 23:42:23
【问题描述】:
我正在为 Kotlin 开发一个 KSP 注释处理器。代码在编译期间正确生成,我可以在输出目录中看到生成的类。现在我想通过 JUnit 和“com.github.tschuchortdev.KotlinCompilation”测试我的注释处理器。如果我调用 compile 方法,将生成代码,我可以在 Temp-Directory 中看到生成的类,但如果我尝试加载该类,则会收到“java.lang.ClassNotFoundException:test.pack.TestClassDslBuilder”异常。我希望代码是不言自明的。 我的问题是:为什么类没有编译并且不可加载?可能缺少 kompiler 的配置。
@BeforeEach
fun setup() {
val kotlinSource = SourceFile.kotlin(
"TestClass.kt", """
package test.pack
import yy.xxx.dsl.builder.annotation.DslBuilder
@DslBuilder
class TestClass {
}
"""
)
val compilation = KotlinCompilation().apply {
sources = listOf(kotlinSource)
symbolProcessorProviders = listOf(DslBuilderProcessorProvider())
//workingDir =
inheritClassPath = true
verbose = false
//messageOutputStream = System.out
kspIncremental = true
}
compilationResult = compilation.compile()
assertEquals(KotlinCompilation.ExitCode.OK, compilationResult.exitCode)
// The next line leads to java.lang.ClassNotFoundException
compilationResult.classLoader.loadClass("test.pack.TestClassDslBuilder")
}
【问题讨论】:
-
目前可能无法加载类。但它与 kapt 注释处理器一起工作。
-
不知道有没有用,不过这篇文章proandroiddev.com/ksp-fact-or-kapt-7c7e9218c575有一些测试ksp的小技巧。它包括一个指向编译器测试工具的链接,该工具具有 ksp 测试工具github.com/tschuchortdev/kotlin-compile-testing。
-
文件生成了吗?您需要断言该文件存在,然后断言它的内容或类加载能够加载该类。