I wanted to test a class using an annotation processor using junit, so I used Aptina Unit at first, but due to adult circumstances, I had to use compile-testing, so I forgot to use it. It is written here so that it does not exist.
compile-testing github https://github.com/google/compile-testing
(´-`) .. oO (I'm flirting when I see English.)
Click here for other referenced pages
http://blog.64p.org/entry/2015/03/26/055347
http://hisaichi5518.hatenablog.jp/entry/2017/09/21/213423
http://blog.duck8823.com/entry/2016/05/07/095947
(´-`) .. oO (Reliable Japanese)
In pom.xml, write:
<dependency>
  <groupId>com.google.testing.compile</groupId>
  <artifactId>compile-testing</artifactId>
  <version>0.12</version>
  <scope>test</scope>
</dependency>
(´-`) .. oO (I want to stop here.)
This is a sample test code written to check the source output by the processor.
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import javax.tools.JavaFileObject;
import org.junit.Test;
import com.google.common.io.Resources;
import com.google.testing.compile.Compilation;
import com.google.testing.compile.JavaFileObjects;
import static com.google.testing.compile.Compiler.javac;
import static com.google.common.truth.Truth.assert_;
import static com.google.testing.compile.JavaSourceSubjectFactory.javaSource;
public class MyProcessorTest {
	@Test
	public void test_Processor output check(){
		MyProcessor processor = new MyProcessor();
		
		// assert
		assert_().about(javaSource())
			.that(JavaFileObjects.forResource(Resources.getResource("HelloWorld.java")))
			.processedWith(processor)
			.compilesWithoutError()
			.and()
			.generatesSources(JavaFileObjects.forSourceString("foo.bar.baz.Blah", "package foo.bar.baz;\n"
					+ "\n"
					+ "import java.lang.String;\n"
					+ "import javax.annotation.Generated;\n"
					+ "\n"
					+ "@Generated({\"me.geso.sample.hello.MyProcessor\"})\n"
					+ "public class Blah {\n"
					+ "  public String hello() {\n"
					+ "    return \"hello\";\n"
					+ "  }\n"
					+ "}"));
	}
}
You can see that foo.bar.baz.Blah matches the following parameters with generatesSources ().
Test when you want to check for errors
	@Test
	public void test_process_error() throws Exception {
		File stub = new File(System.getProperty("user.dir") + "/src/test/java/jp/co/processor/MyProErrStub.java");
		
        assert_().about(JavaSourceSubjectFactory.javaSource())
        	.that(JavaFileObjects.forResource(stub.toURI().toURL()))
        	.processedWith(new MyProcessor())
        	.failsToCompile();
	}
failsToCompile ().Recommended Posts