diff --git a/java-checks-test-sources/default/src/test/java/checks/tests/AssertionsWithoutMessageCheckSample.java b/java-checks-test-sources/default/src/test/java/checks/tests/AssertionsWithoutMessageCheckSample.java index aba4554a446..5a772680eda 100644 --- a/java-checks-test-sources/default/src/test/java/checks/tests/AssertionsWithoutMessageCheckSample.java +++ b/java-checks-test-sources/default/src/test/java/checks/tests/AssertionsWithoutMessageCheckSample.java @@ -14,6 +14,9 @@ class AssertionsWithoutMessageCheckSample { void foo() { + org.testng.Assert.assertTrue(true, "msg"); // Compliant + org.testng.Assert.assertTrue(true); // Noncompliant + org.testng.AssertJUnit.assertTrue(true); // Noncompliant org.assertj.core.api.Assertions.assertThat("").usingComparator(null).as("a").isEqualTo(222); // Compliant org.junit.Assert.assertTrue(true); // Noncompliant {{Add a message to this assertion.}} // ^^^^^^^^^^ diff --git a/java-checks/src/main/java/org/sonar/java/checks/tests/AssertionsWithoutMessageCheck.java b/java-checks/src/main/java/org/sonar/java/checks/tests/AssertionsWithoutMessageCheck.java index b44a529bdff..37e1dd09962 100644 --- a/java-checks/src/main/java/org/sonar/java/checks/tests/AssertionsWithoutMessageCheck.java +++ b/java-checks/src/main/java/org/sonar/java/checks/tests/AssertionsWithoutMessageCheck.java @@ -82,7 +82,7 @@ protected MethodMatchers getMethodInvocationMatchers() { return MethodMatchers.or( MethodMatchers.create() .ofTypes("org.junit.jupiter.api.Assertions", "org.junit.Assert", "junit.framework.Assert", "org.fest.assertions.Fail", - "org.assertj.core.api.Fail") + "org.assertj.core.api.Fail", "org.testng.Assert", "org.testng.AssertJUnit") .name(name -> name.startsWith(ASSERT) || "fail".equals(name)).withAnyParameters().build(), FEST_LIKE_ABSTRACT_ASSERT ); @@ -105,11 +105,21 @@ protected void onMethodInvocationFound(MethodInvocationTree mit) { checkFestLikeAssertion(mit, symbol, reportLocation); } else if (type.is("org.junit.jupiter.api.Assertions")) { checkJUnit5(mit, reportLocation); - } else if (mit.arguments().isEmpty() || !isString(mit.arguments().get(0)) || isAssertingOnStringWithNoMessage(mit)) { + } else if (mit.arguments().isEmpty() || !hasMessageArg(mit, type) || isAssertingOnStringWithNoMessage(mit)) { reportIssue(reportLocation, MESSAGE); } } + /** + * True if the call has a message argument. Such an argument is a string + * and it is the first of the last argument (depending on the assertion library). + */ + private static boolean hasMessageArg(MethodInvocationTree mit, Type type) { + int expectedMessageArgIndex = (type.is("org.testng.Assert") || type.is("org.testng.AssertJUnit")) ? 1 : 0; + List args = mit.arguments(); + return expectedMessageArgIndex < args.size() && isString(args.get(expectedMessageArgIndex)); + } + private void checkFestLikeAssertion(MethodInvocationTree mit, Symbol symbol, IdentifierTree reportLocation) { if (isConstructor(symbol)) { return;