How to write automated unit tests for java annotation processor?

前端 未结 6 1341
遇见更好的自我
遇见更好的自我 2021-01-31 09:24

I\'m experimenting with java annotation processors. I\'m able to write integration tests using the \"JavaCompiler\" (in fact I\'m using \"hickory\" at the moment). I can run the

6条回答
  •  被撕碎了的回忆
    2021-01-31 09:52

    This is an old question, but it seems that the state of annotation processor testing hadn't gotten any better, so we released Compile Testing today. The best docs are in package-info.java, but the general idea is that there is a fluent API for testing compilation output when run with an annotation processor. For example,

    ASSERT.about(javaSource())
        .that(JavaFileObjects.forResource("HelloWorld.java"))
        .processedWith(new MyAnnotationProcessor())
        .compilesWithoutError()
        .and().generatesSources(JavaFileObjects.forResource("GeneratedHelloWorld.java"));
    

    tests that the processor generates a file that matches GeneratedHelloWorld.java (golden file on the class path). You can also test that the processor produces error output:

    JavaFileObject fileObject = JavaFileObjects.forResource("HelloWorld.java");
    ASSERT.about(javaSource())
        .that(fileObject)
        .processedWith(new NoHelloWorld())
        .failsToCompile()
        .withErrorContaining("No types named HelloWorld!").in(fileObject).onLine(23).atColumn(5);
    

    This is obviously a lot simpler than mocking and unlike typical integration tests, all of the output is stored in memory.

提交回复
热议问题