[java] AvoidLiteralsInIfCondition - add test case for #4514

Closes #4514
This commit is contained in:
Andreas Dangel
2023-04-27 19:59:24 +02:00
parent afe1613c93
commit daf574a888
3 changed files with 34 additions and 0 deletions

View File

@ -505,6 +505,7 @@ Language specific fixes:
* [#4493](https://github.com/pmd/pmd/issues/4493): \[java] MissingStaticMethodInNonInstantiatableClass: false-positive about @<!-- -->Inject
* [#4505](https://github.com/pmd/pmd/issues/4505): \[java] ImplicitSwitchFallThrough NPE in PMD 7.0.0-rc1
* [#4513](https://github.com/pmd/pmd/issues/4513): \[java] UselessOperationOnImmutable various false negatives with String
* [#4514](https://github.com/pmd/pmd/issues/4514): \[java] AvoidLiteralsInIfCondition false positive and negative for String literals when ignoreExpressions=true
* java-multithreading
* [#2537](https://github.com/pmd/pmd/issues/2537): \[java] DontCallThreadRun can't detect the case that call run() in `this.run()`
* [#2538](https://github.com/pmd/pmd/issues/2538): \[java] DontCallThreadRun can't detect the case that call run() in `foo.bar.run()`

View File

@ -566,6 +566,7 @@ public void checkRequests() {
// with rule property "ignoreExpressions" set to "false"
if (i == pos + 5) {} // violation: magic number 5 within an (additive) expression
if (i == pos + SUFFIX_LENGTH) {} // preferred approach
if (i == 5 && "none".equals(aString)) {} // 2 violations: magic number 5 and literal "none"
}
]]>
</example>

View File

@ -144,4 +144,36 @@ public class AvoidLiteralsInIfConditionWithExpressions {
}
]]></code>
</test-code>
<code-fragment id="code-for-4514"><![CDATA[
public class AvoidLiteralsInIfCondition {
private static final int MY_CONSTANT = 1;
public void test(int i, String s) {
if ("test".equals(s)) {} // expected violation is missing (false negative)
if (i == 1) {} // expected violation
// the following literals should be ignored because ignoreExpression=true
if (i == MY_CONSTANT && "test".equals(s)) {} // violation for "test" only (false positive)
if (i == 1 && "test".equals(s)) {} // violation for "test" (false positive)
}
}
]]></code-fragment>
<test-code>
<description>[java] AvoidLiteralsInIfCondition false positive and negative for String literals when ignoreExpressions=true #4514</description>
<rule-property name="ignoreExpressions">true</rule-property>
<rule-property name="ignoreMagicNumbers">-1,0</rule-property>
<expected-problems>2</expected-problems>
<expected-linenumbers>4,5</expected-linenumbers>
<code-ref id="code-for-4514"/>
</test-code>
<test-code>
<description>[java] AvoidLiteralsInIfCondition false positive and negative for String literals when ignoreExpressions=false #4514</description>
<rule-property name="ignoreExpressions">false</rule-property>
<rule-property name="ignoreMagicNumbers">-1,0</rule-property>
<expected-problems>5</expected-problems>
<expected-linenumbers>4,5,8,9,9</expected-linenumbers>
<code-ref id="code-for-4514"/>
</test-code>
</test-data>