Hi,
I’m trying to create my first custom rule, based on sonar-java/docs/CUSTOM_RULES_101.md at master · SonarSource/sonar-java · GitHub.
This is the class I created:
package org.sonar.samples.java.checks;
import org.sonar.check.Rule;
import org.sonar.java.checks.methods.AbstractMethodDetection;
import org.sonar.plugins.java.api.semantic.MethodMatchers;
import org.sonar.plugins.java.api.tree.MethodInvocationTree;
import static org.sonar.plugins.java.api.semantic.MethodMatchers.ANY;
@Rule(key = "MyFirstCustomRule")
public class MyFirstCustomCheck extends AbstractMethodDetection {
private static final String[] ASSERTION_CLASSES = {
// JUnit4
"org.junit.Assert", "junit.framework.TestCase",
// JUnit4 (deprecated)
"junit.framework.Assert",
// JUnit5
"org.junit.jupiter.api.Assertions" };
@Override
protected MethodMatchers getMethodInvocationMatchers() {
return MethodMatchers.create()
.ofTypes(ASSERTION_CLASSES)
.names("assertEquals")
.addParametersMatcher(ANY, ANY)
.build();
}
@Override
protected void onMethodInvocationFound(MethodInvocationTree mit) {
//reportIssue(ExpressionUtils.methodName(mit), "Use \"org.assertj.core.api.Assertions.assertThat\" instead." + context.getJavaVersion()
reportIssue(mit.methodSelect(), "Use \"org.assertj.core.api.Assertions.assertThat\" instead." + context.getJavaVersion()
.java8CompatibilityMessage());
}
}
This is the test class:
package org.sonar.samples.java.checks;
import org.junit.jupiter.api.Test;
import org.sonar.java.checks.verifier.CheckVerifier;
class MyFirstCustomCheckTest {
@Test
void aaa() {
CheckVerifier.newVerifier()
//.onFile(FILENAME)
.onFile("src/test/files/MyFirstCustomCheck.java")
.withCheck(new MyFirstCustomCheck())
//.withJavaVersion(8)
.verifyIssues();
}
}
And the test file:
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.assertj.core.api.Assertions.assertThat;
public class MyClass {
int result = 5;
void t1(){
assertEquals(5, result); // Noncompliant
assertThat(result).isEqualTo(5);
}
}
I debug the code, and in the MethodMatchersBuilder, the first line does not match, when it should.
public boolean matches(MethodInvocationTree mit) {
IdentifierTree id = getIdentifier(mit);
return this.matches(id.symbol(), getCallSiteType(mit));
}
I see that id.symbol returns an UnknownSymbol, while in another test from the workspace I have downloaded it returns a JMethodSymbol.
What am I doing wrong?
Thanks!