Sunday, November 18, 2007

IDEA Seems to have Built-In Knowledge about JUnit API

Hmm, I have always liked IDEAs all-time present analysis of my AST when typing, which for instance can give me a warning, if some variable could be null when referenced. I think IDEA analyzes the possible execution paths of the code, and then determines if some variable might be null in a place where it is referenced. The other day I noticed, that IDEA must have built-in knowledge about JUnit, because it seems to use the contract of assertNotNull, in its analysis of nullable variables.

In this little example (JUnit) testcase:
public class TestBlahBlah extends TestCase {
public void testBlah() {
String s = null;
System.out.println("s.length() = " + s.length());
}
}
IDEA promptly warns me about the expression s.length() might produce NullPointerException, and indeed, it will. But, if I add an assertNotNull(s), so that the test looks like this instead:
    ...
public void testBlah() {
String s = null;
assertNotNull(s);
System.out.println("s.length() = " + s.length());
}
The warnings goes away. Nice! And it is not just because the variable has been used to something else in between. If I add assertEquals(s, s) in place of assertNotNull, the warning pops up again.

Just one of the little niceties of a great IDE!

1 comment:

Ricky Clarkson said...

It would be great if we could hook into that as developers. For example, I have my own assertNotNull that takes varargs, e.g.:

assertNotNull(x,y,z);

and IDEA doesn't know about its semantics, and I don't know how to tell IDEA about it.