Skip navigation links

@CheckReturnValue

Package com.google.testing.compile

This package contains classes that let you compile Java source code in tests and make assertions about the results.

See: Description

Package com.google.testing.compile Description

This package contains classes that let you compile Java source code in tests and make assertions about the results. This lets you easily test annotation processors without forking javac or creating separate integration test projects.

A simple example that tests that compiling a source file succeeded is:

 Compilation compilation =
     javac().compile(JavaFileObjects.forSourceString("HelloWorld", "final class HelloWorld {}");
 assertThat(compilation).succeeded();
 

A similar example that tests that compiling a source file with an annotation processor succeeded without errors or warnings (including compiling any source files generated by the annotation processor) is:

 Compilation compilation =
     javac()
         .withProcessors(new MyAnnotationProcessor())
         .compile(JavaFileObjects.forSourceString("HelloWorld", "final class HelloWorld {}");
 assertThat(compilation).succeededWithoutWarnings();
 

You can make assertions about the files generated during the compilation as well. For example, the following snippet tests that compiling a source file with an annotation processor generates a source file equivalent to a golden file:

 Compilation compilation =
     javac()
         .withProcessors(new MyAnnotationProcessor())
         .compile(JavaFileObjects.forResource("HelloWorld.java"));
 assertThat(compilation).succeeded();
 assertThat(compilation)
     .generatedSourceFile("GeneratedHelloWorld")
     .hasSourceEquivalentTo(JavaFileObjects.forResource("GeneratedHelloWorld.java"));
 

You can also test that errors or other diagnostics were reported. The following tests that compiling a source file with an annotation processor reported an error:

 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);
 
Skip navigation links

Copyright © 2013–2022. All rights reserved.