在junit测试中获取一个类作为javax.lang.model.element.Element [英] Get a class as javax.lang.model.element.Element in junit tests
问题描述
我想测试我的实用程序类ElementUtils,但我不知道如何获得一个类作为一个元素。在AnnotationProcessors中,我通过使用以下代码获得我的元素:
I would like to test my utility class ElementUtils but I don't know how to get a class as an Element. In AnnotationProcessors I get my elements by using the following code
Set<? extends Element> elements = roundEnvironment.getElementsAnnotatedWith(annotation);
但由于RoundEnvironment在测试中不可用,因此这不是一个选项。
but since the RoundEnvironment is not available in the tests this is not an option.
有没有办法获得一个类作为javax.lang.model.element.Element?
Is there any way to get a class as an javax.lang.model.element.Element?
推荐答案
您可以使用JUnit @Rule调用在测试期间运行的编译器,此时您可以使用Types和Elements实用程序类来获取TypeMirror和Element实例。
You can use a JUnit @Rule to invoke a compiler run during the test, at which point you may then use Types and Elements utility classes to obtain TypeMirror and Element instances.
这样的规则已创建,并且是 http://github.com/google的一部分/ compile-testing ,因此可以使用:
Such a rule has been created and is a part of http://github.com/google/compile-testing and can be used thusly:
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.
}
你可以做些什么操作(无论是测试还是其他)类型镜像和元素实例可以在 http://github.com/google/auto 项目中找到公共子模块,它包含用于方便地管理这些java.lang.model类的实用程序。
Some of what stuff you can do to manipulate (whether in tests or otherwise) TypeMirror and Element instances can be found in the http://github.com/google/auto project in the common sub-module, which contains utilities for managing these java.lang.model classes conveniently.
这篇关于在junit测试中获取一个类作为javax.lang.model.element.Element的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!