java - 测试 AbstractProcessor(Java 在编译时的注解处理)

标签 java unit-testing testing annotations preprocessor

我正在编写一个依赖于 AbstractProcessor 类的库,因为我想编写一个很棒的库,所以我也希望有一个很好的覆盖范围。由于预处理器 在编译时工作,我不确定如何测试该代码。

我有一些构建应该失败的测试场景。但是我该如何测试呢?我是否必须执行 gradle 并检查退出代码?是否有一种干净的方法来验证构建失败是由预期原因引起的,还是我还需要编写某种解析器?恕我直言,这将是一个很好的覆盖范围的巨大开销。

对于那些需要示例的人:

@SupportedAnnotationTypes("eu.rekisoft.java.preprocessor.Decorator")
@SupportedSourceVersion(SourceVersion.RELEASE_7)
public class ExamplePreprocessor extends AbstractProcessor {

    public ExamplePreprocessor() {
        super();
    }

    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        for(Element elem : roundEnv.getElementsAnnotatedWith(Decorator.class)) {
            Method method = Method.from((ExecutableElement)elem);
            if(!method.matchesTypes(String.class, StringBuilder.class)) {
                processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "No! " + elem + " has the wrong args!");
            } else {
                processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, "Yey " + elem + " this is fine!");
            }
        }
        return true; // no further processing of this annotation type
    }
}

这是一个无法编译的类:

public class AnnotationedExample {
    @Decorator
    public int breakBuild() {
        return -1;
    }

    @Decorator
    public String willCompile(StringBuilder sb) {
        return null;
    }
}

最后是无聊的注解:

@Retention(RetentionPolicy.SOURCE)
@Target(ElementType.METHOD)
public @interface Decorator {
}

您还可以在 GitHub 处 checkout 项目你只需要 checkout 项目并执行 gradlew cJ。您可能需要修复 linux 和 mac 上脚本缺少的 x 权限。

最佳答案

Google 有一个非常好的 API 用于测试编译。 (https://github.com/google/compile-testing)。下面是一个示例,用于测试 .java 文件是否可以通过使用 junit 的处理器进行编译。

package org.coffeebag.processor;

import com.google.testing.compile.JavaFileObjects;
import com.google.testing.compile.JavaSourceSubjectFactory;
import org.junit.Test;

import java.io.File;
import java.net.MalformedURLException;

import static org.truth0.Truth.ASSERT;

public class ExampleTest {

    @Test
    public void EmptyClassCompiles() throws MalformedURLException {
        final MyProcessor processor = MyProcessor.testMode();
        File source = new File("path/to/test/file.java");
        ASSERT.about(JavaSourceSubjectFactory.javaSource())
                .that(JavaFileObjects.forResource(source.toURI().toURL()))
                .processedWith(processor)
                .compilesWithoutError();
    }
}

关于java - 测试 AbstractProcessor(Java 在编译时的注解处理),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38753986/

相关文章:

java - 在java中读取TCP问题

python - 模拟类的构造

android - Robolectric with Gradle:软件包org.robolectric不存在

javascript - 如何测试 Node 数据分块功能

java - 使用比较器 "offtopic"是不好的 java 风格吗?

java - Struts2 ActionSupport getTexts() 不起作用

java - Spring,使用 POST 重定向到外部 url

ruby-on-rails-3 - Rspec 测试属性是否被更新

unit-testing - 在 xUnit.net 中,是否可以按顺序运行测试?

testing - 如何在 Leiningen 中声明测试范围依赖项?