https://kotlinlang.org logo
Title
r

rnpy

11/19/2018, 7:00 AM
anyone has experience with writing annotation processors that generate kotlin code? wondering if there was a way to test compiled code the same way we can test Java with
compile-testing
library? (https://github.com/google/compile-testing) currently I'm testing generated sources with a few regex, but that's really not optimal 😕
u

Uzi Landsmann

11/19/2018, 7:18 AM
r

rnpy

11/19/2018, 7:20 AM
I use KotlinPoet to generate the sources, question is how to test the generated code
With
compile-testing
when generating Java you can write tests like this:
Compilation compilation =
    javac()
        .withProcessors(new MyAnnotationProcessor())
        .compile(JavaFileObjects.forResource("HelloWorld.java"));
assertThat(compilation).succeeded();
assertThat(compilation)
    .generatedSourceFile("GeneratedHelloWorld")
    .hasSourceEquivalentTo(JavaFileObjects.forResource("GeneratedHelloWorld.java"));
Or for errors:
JavaFileObject helloWorld = JavaFileObjects.forResource("HelloWorld.java");
Compilation compilation =
    javac()
        .withProcessors(new NoHelloWorld())
        .compile(helloWorld);
assertThat(compilation).failed();
assertThat(compilation)
    .hadErrorContaining("No types named HelloWorld!")
    .inFile(helloWorld)
    .onLine(23)
    .atColumn(5);
to be more specific, currently I actually use
compile-testing
to compile the code in my tests (writing the sources I compile in my tests in Java), but the processor generate Kotlin code, so I can use some features like error cases, but I can't use any java-specific things like
generatedSourceFile
or
hasSourceEquivalentTo
(both only handle Java stuff), instead I redirect the output and test it myself (with a few regexp)
u

Uzi Landsmann

11/19/2018, 7:56 AM
Sorry, I’m no expert, just experimenting a bit with kotlinpoet myself. Haven’t got around to testing yet