我有一个使用SonarJava创建自定义规则的任务。规则的目的是检查方法。如果方法使用@Test注释,则还需要具有@TestInfo注释,且其参数不能为空testCaseId。
这是我准备的:
public class AvoidEmptyTestCaseIdParameterRule extends IssuableSubscriptionVisitor {
private static final String TEST_ANNOTATION_PATH = "org.testng.annotations.Test";
private static final String TEST_INFO_ANNOTATION_PATH = "toolkit.utils.TestInfo";
@Override
public List<Tree.Kind> nodesToVisit() {
return ImmutableList.of(Tree.Kind.METHOD);
}
@Override
public void visitNode(Tree tree) {
MethodTree methodTree = (MethodTree) tree;
if (methodTree.symbol().metadata().isAnnotatedWith(TEST_ANNOTATION_PATH)) {
if (methodTree.symbol().metadata().isAnnotatedWith(TEST_INFO_ANNOTATION_PATH)) {
List<AnnotationInstance> annotations = methodTree.symbol().metadata().annotations();
for (int i = 0; i < annotations.size(); i++) {
if (annotations.get(i).symbol().name().equals("TestInfo")
&& !testInfoAnnotationContainsNonEmptyTestCaseIdParameter(annotations.get(i))) {
reportIssue(methodTree.simpleName(),
"Method annotated with @TestInfo should have not empty testCaseId parameter");
}
}
} else {
reportIssue(methodTree.simpleName(),
"Method annotated with @Test should also be annotated with @TestInfo");
}
}
}
private boolean testInfoAnnotationContainsNonEmptyTestCaseIdParameter(AnnotationInstance annotation) {
return <--this is where I stuck-->;
}
}
这是我的测试类的外观:
public class TestClass {
@Test
@TestInfo(testCaseId = "", component = "Policy.IndividualBenefits")
public void testMethod() {
}
}
问题:
-是否可以获取注释参数(正确或作为字符串行)?
-还有其他方法可以获取此参数吗?
答案 0 :(得分:0)
我知道了。我改用Tree.Kind.ANNOTATION。 这是用于搜索所需参数的代码:
Arguments arguments = annotationTree.arguments();
if (!arguments.isEmpty()) {
for (int i = 0; i < arguments.size(); i++) {
String parameter = arguments.get(i).firstToken().text();
String parameterValue = arguments.get(i).lastToken().text();
if (isParameterTestCaseId(parameter) && isTestCaseIdEmpty(parameterValue)) {
reportIssue(arguments.get(i),
"Method annotated with @TestInfo should have not empty testCaseId parameter");
}
}
}
检查参数及其值的方法:
private boolean isParameterTestCaseId(String parameter) {
return parameter.matches("testCaseId");
}
private boolean isTestCaseIdEmpty(String parameterValue) {
return parameterValue.length() != 0;
}