Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
AnnotationProcessorTest with JUnit
import org.junit.Before;
import org.junit.BeforeClass;
import javax.annotation.processing.Processor;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Locale;
/**
* Your unit tests of AnnotationProcessors should inherit this class
*/
public abstract class AnnotationProcessorTest {
private static JavaCompiler compiler;
private StandardJavaFileManager fileManager;
private DiagnosticCollector<JavaFileObject> collector;
/**
* url to the files you want to compile.
*/
public abstract String[] getClassesToCompile();
/**
* processors you wish to test.
*/
public abstract Iterable<? extends Processor> getProcessors();
@BeforeClass
public static void initClass() throws Exception {
compiler = ToolProvider.getSystemJavaCompiler();
}
@Before
public void initTest() throws Exception {
collector = new DiagnosticCollector<JavaFileObject>();
fileManager = compiler.getStandardFileManager(collector, Locale.US, Charset.forName("UTF-8"));
}
/**
* Call this from your unit test. It will return the results of the compilation as a CompilationResult
*/
protected CompilationResult testCompilation() throws Exception {
OutputStreamWriter stdout = new OutputStreamWriter(new ByteArrayOutputStream());
JavaCompiler.CompilationTask task = compiler.getTask(stdout, fileManager, collector, null,
null, fileManager.getJavaFileObjects(getClassesToCompile()));
task.setProcessors(getProcessors());
Boolean result = task.call();
String stdoutString = new String(new ByteArrayOutputStream().toByteArray());
return new CompilationResult(collector.getDiagnostics(), stdoutString, result);
}
/**
* results of the compilation.
*/
protected static class CompilationResult {
private List<Diagnostic<? extends JavaFileObject>> diagnostics;
private String stdoutString;
private Boolean result;
public CompilationResult(List<Diagnostic<? extends JavaFileObject>> diagnostics,
String stdoutString, Boolean result) {
this.diagnostics = diagnostics;
this.stdoutString = stdoutString;
this.result = result;
}
/**
* Any errors or diagnostics that occured during compilation
*/
public List<Diagnostic<? extends JavaFileObject>> getDiagnostics() {
return diagnostics;
}
/**
* stdout of the compilation
*/
public String getStdoutString() {
return stdoutString;
}
/**
* wether the compilation exited successfully
*/
public Boolean isSuccess() {
return result;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment