we have a habit in our company that when a bug is reported we do following steps:
Now I came across a piece of legacy code with very easy bug. Situation looks like follows:
public final class SomeClass {
...
public void someMethod(Parameter param) {
try {
if (param.getFieldValue("fieldName").equals("true")) { // Causes NullPointerException
...
}
} catch (Exception ex) {
log.warn("Troubles ...", ex);
}
}
}
The problem here is that fieldName
is not mandatory, so if not present, you get NPE. The obvious fix is:
if ("true".equals(param.getFieldValue("fieldName"))) {
...
}
My question is how to write a unit test to make the method fail. If I pass in a message which doesn't contain the fieldName
it just logs the NPE but it won't fail ...
You may think what the method does? I can test the effect the method has. Unfortunatelly it communicates with some remote system so this will require a huge integration test which seems to be overkill with such a small and straiht-forward bug.
Note that it will be really hard if not impossible to make any changes in the code that are not directly causing the bug. So changing the code just to make it easier to test will probably not be an option. It's quite scary legacy code and everybody is really afraid to touch it.
You could do several things: