//不合规注释用法 - SonarQube 自定义规则



我正在尝试为我的项目编写一些SONARQUBE自定义规则。 阅读以下文档后 - https://docs.sonarqube.org/display/PLUG/Writing+Custom+Java+Rules+101 和 https://github.com/SonarSource/sonar-custom-rules-examples, 我创建了一个自定义规则,如下所示 -

规则文件:

@Rule(key = "MyAssertionRule")
public class FirstSonarCustomRule extends BaseTreeVisitor implements JavaFileScanner {
private static final String DEFAULT_VALUE = "Inject";
private JavaFileScannerContext context;
/**
* Name of the annotation to avoid. Value can be set by users in Quality
* profiles. The key
*/
@RuleProperty(defaultValue = DEFAULT_VALUE, description = "Name of the annotation to avoid, without the prefix @, for instance 'Override'")
protected String name;
@Override
public void scanFile(JavaFileScannerContext context) {
this.context = context;
System.out.println(PrinterVisitor.print(context.getTree()));
scan(context.getTree());
}
@Override
public void visitMethod(MethodTree tree) {
List<StatementTree> statements = tree.block().body();
for (StatementTree statement : statements) {
System.out.println("KIND IS " + statement.kind());
if (statement.is(Kind.EXPRESSION_STATEMENT)) {
if (statement.firstToken().text().equals("Assert")) {
System.out.println("ERROR");
}
}
}
}
}

测试类:

public class FirstSonarCustomRuleTest {
@Test
public void verify() {
FirstSonarCustomRule f = new FirstSonarCustomRule();
f.name = "ASSERTION";
JavaCheckVerifier.verify("src/test/files/FirstSonarCustom.java", f);
}
}

最后 -Test文件:

class FirstSonarCustom {
int aField;
public void methodToUseTestNgAssertions() {
Assert.assertTrue(true);
}
}

上面的测试文件后来将成为我项目的源代码。 根据 SONAR 文档 -//不合规是我的测试文件中的强制性注释。因此,我的第一个问题是我是否也应该在我的源代码中的所有位置添加此注释? 如果是 - 有什么方法可以避免添加此注释,因为我不想重新添加代码重构练习。

有人可以建议我在这里需要做什么吗?

我正在使用SONARQUBE 6.3。

此注释仅由测试框架(JavaCheckVerifier类(用于测试规则的实现。它在任何方面都不是强制性的,并且肯定您在实际代码中不需要它。

最新更新