为java编写自定义声纳规则时如何处理assertionError

tur*_*ist 2 java rules sonarqube

我正在使用 java 为 java 编写自定义声纳规则。我遇到了一个无法轻易修复的断言错误。我确信源代码是正确的。但测试用例无法通过。我想知道在使用 TDD 流程时我应该关心什么以及如何解决它。

public class logTCheckFile {
    private static Logger logger = Logger.getLogger(logTCheckFile.class);
    public void loggingWithID(String nonsense) throws myException{
        logger.error("errorID:20160801 this is an error");
        return;
    }

    public void loggingWithoutID(String nonsens){
        try{
            logger.error("this is an error");
        }catch(NullPointerException e){
            logger.error("what",e);
        }
        return;
    }

    public void specific(){
        logger.error("only the logger");
        try{
            logger.error("this is an error");
        }catch(NullPointerException e){
            logger.error("without an exception");
        }
        return;
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在测试上面的文件,我编写了一条规则来测试未抛出的异常是否打印在记录器中。

消息是AssertionError: Unexpected at [20](这是失败堆栈跟踪的图片)

我编写的检查文件的代码如下:

public class logTCheck extends  IssuableSubscriptionVisitor {


Logger log = Logger.getLogger(logTCheck.class);

@Override
public List<Kind> nodesToVisit() {
    return ImmutableList.of(Kind.METHOD);
}

@Override
public void visitNode(Tree tree){
    MethodTree method = (MethodTree) tree;
    if(method.throwsClauses().size()==0){
        log.info("this method does not have a throw clause");
        BlockTree bt = method.block();
        for(StatementTree st:bt.body()){
            if(st.is(Kind.TRY_STATEMENT)){
                TryStatementTree tst = (TryStatementTree) st;
                for(CatchTree ct:tst.catches()){
                    for(StatementTree state:ct.block().body()){
                        ExpressionStatementTree ex = (ExpressionStatementTree)state;
                        MethodInvocationTree mit = (MethodInvocationTree) ex.expression();
                        if(mit.arguments().size()!=2){
                            log.error(method.simpleName());
                            reportIssue(method.simpleName(), "you didn't print the exception in the log");
                        }
                    }
                }
            }
        }
    };
 }
}
Run Code Online (Sandbox Code Playgroud)

Sto*_*ica 5

消息是 AssertionError: Unexpected at [20]

这意味着测试数据的第 20 行包含违反您正在检查的规则的行为。

您需要告诉验证者这种违规行为是故意存在的。执行此操作的一个简单方法是在违规之前的行中添加如下注释:

// Noncompliant@+1 {{the violation message}}
Run Code Online (Sandbox Code Playgroud)

@+1意味着违规行为在下一行。适当调整数量。

注释必须位于行的开头,否则前面可能有空格//

其中包含的违规消息{{...}}是可选的,但强烈推荐。在进行 TDD 时,输入正确消息的一个简单方法是添加类似{{x}}会导致测试失败的内容,然后您可以将测试输出中的消息复制到测试文件中来修复它。