And*_*Dev 4 java testing class annotation-processing
我想测试我的实用程序类 ElementUtils,但我不知道如何将类作为 Element。在 AnnotationProcessors 中,我使用以下代码获取元素
Set<? extends Element> elements = roundEnvironment.getElementsAnnotatedWith(annotation);
Run Code Online (Sandbox Code Playgroud)
但由于 RoundEnvironment 在测试中不可用,因此这不是一个选项。
有没有办法将类作为 javax.lang.model.element.Element 获取?
您可以使用 JUnit @Rule 在测试期间调用编译器运行,此时您可以使用 Types 和 Elements 实用程序类来获取 TypeMirror 和 Element 实例。
这样的规则已经创建并且是http://github.com/google/compile-testing的一部分,可以这样使用:
public @Rule CompilationRule rule = new CompilationRule();
private Elements elements;
private Types types;
@Before
public void setup() {
elements = rule.getElements();
types = rule.getTypes();
}
@Test void testStuff() {
TypeElement typeElement = elements.getTypeElement("some.fully.qualified.ClassName");
// do stuff.
}
Run Code Online (Sandbox Code Playgroud)
您可以在http://github.com/google/auto项目的公共子模块中找到一些可以操作(无论是在测试中还是其他方式)TypeMirror 和 Element 实例的东西,其中包含用于管理这些的实用程序java.lang.model 类很方便。