Search code examples
javaunit-testingequals

Assertions about comparing different types: redundant and silly?


So I have this Java code that overrides equals for a class:

@Override public boolean equals(Object o) {
    if (o instanceof NumeroSeccion) {
        NumeroSeccion numSec = (NumeroSeccion) o;
        return Arrays.equals(this.valor, numSec.valor);
    } else {
        return false;
    }
}

which basically follows the common rule about checking if both objects are of the same class before doing anything else. Others prefer using getClass(), but the idea is the same.

Now I wrote some tests for it, including:

void notEqualsOtherClass() {
    NumeroSeccion ns1 = new NumeroSeccion("1.2.3.4.5");
    String ns2Str = "1.2.3.4.5";
    assertNotEquals(ns1, ns2Str);
}

According to IntelliJ IDEA, this is "possibly redundant":

Possibly redundant assertion: incompatible types are compared 'NumeroSeccion' and 'String'

According to Sonar static code analysis, this is a "silly equality check":

Silly equality checks should not be made. Comparisons of dissimilar types will always return false. The comparison and all its dependent code can simply be removed. This includes: comparing unrelated classes.

Is it actually redundant checking class types or add a test for this check, or are all these tools giving bad advice?


Solution

  • The advice given by the warning is valid for production code. Testing code is a special case, where you are deliberately doing something wrong in order to test something. So, the warning is perfectly legitimate, but it just so happens to be inapplicable in testing code.

    You can safely suppress the warning in that specific line of test code only.

    Alternatively, instead of suppressing the warning you can use a trick to fool the compiler (and/or the IDE) so that the warning is not issued. For example, instead of String ns2Str = "1.2.3.4.5"; you may do Object ns2Str = "1.2.3.4.5"; This will probably get rid of the warning.