annotations - 用于注释参数检查的自定义声纳规则
问题描述
我的任务是使用 SonarJava 创建自定义规则。规则的目的是检查方法。如果方法使用@Test 注释,则它还需要具有非空 testCaseId 参数的@TestInfo 注释。
这是我准备的:
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() {
}
}
问题:
- 是否可以获得注释参数(正确或作为字符串行)?
- 还有其他可能的方法来获取这个参数吗?
解决方案
我想到了。我改用 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;
}
推荐阅读
- mysql - MySQL - 我如何获得外键
- c# - 即使在刷新根节点后,我们可以保持子节点扩展吗?在c#中
- apache-spark - Spark bulk insert 的 Elasticsearch 索引速度非常慢
- c++ - 在主窗口之前显示登录对话框并隐藏主窗口按钮
- ios - 从 mac 连接到 nat64 网络的设备中没有互联网
- javascript - 不同的字体源leaflet-awesome-marker和Leaflet-easy-button
- qt - 子类 Keys.onPressed 和 MouseArea.onClicked
- php - 获取多对多关系中的计数以进行记录编辑
- c# - 如何使用 jQuery 在弹出窗口中显示 JSON 解析数据
- xpath - 如何在 Firefox 开发者版中找到 XPath?