简体   繁体   中英

JAVA | Mutation Testing | PiTEST | changed conditional boundary → SURVIVED | Impossible to kill

I am initializing a final int field in a constructor by inspecting a local scale int value with respect to zero.

My code is of the form:

final int scale = calculateScale();
if (scale == 0) {
    this.scale = 0;
} else if (scale > 0) {
    this.scale = 1;
} else {
    this.scale = -1;
}

I would expect this is a common pattern, since a Comparator also returns one of three values, -1, 0 or 1.

Pitest complains about the scale > 0 conditional, declaring the mutation scale >= 0 survives.

However, scale cannot be zero at that point, otherwise it would have entered the first conditional block.

In my opinion, pitest is testing an invalid mutation, and a quick dataflow analysis would reveal scale cannot be zero.

I don't like to modify code to fool pitest, but how could this be expressed such that pitest doesn't complain?

From What is mutation test?

When the application code changes, it should produce different results and cause the unit tests to fail. If a unit test does not fail in this situation, it may indicate an issue with the test suite.

Your code is definitely correct, and I guess your unit test is also correct. So what's wrong?

IMO, what I learn from your example is that.

Mutation Test also aim for Conciseness

Which means there is no space for us to modify the program without changing the behaviour.

Let say someone replaced > with >= accidentally,

...
} else if (scale >= 0) {
    this.scale = 1;
}...

The unit test will still pass, everything will still work. Except the code become confusing. Reader will wonder why it is >= and not > . Not possible to happen? Who knows!

What is the solution?

  1. Refactoring
if (scale < 0) {
    this.scale = -1;
} else if (scale > 0) {
    this.scale = 1;
} else {
    this.scale = 0;
}
  1. Use Integer.signum(int i) , which just return what you need in this case.

Returns the signum function of the specified int value. (The return value is -1 if the specified value is negative; 0 if the specified value is zero; and 1 if the specified value is positive.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM