Wednesday, May 20, 2009

Silly mistake with JUnit assertNotNull

Every so often, I make a fairly simple mistake using the JUnit Assert class:

SomeType myObject = SomeTypeFactory.createInstance();
assertNotNull("unexpectedly had a null myObject");
assertTrue("unexpected return from callSomething",
assertEquals("unexpected result of callAnother",
4, myObject.callAnother());

Do you see the error? Maybe it helps if I point you at the doc?

Well, it's a pretty simple error. I forgot to pass the object that I wanted to check into the assertNotNull method, so I unexpectedly called the other overload of assertNotNull; that is, the overload that just takes a single object. (My message string, after all, is an Object.)

And so my call to assertNotNull is checking to see if the message string is not null, which of course it always is not null, so that assertion never does any good.

And then one day I'm surprised by getting a null pointer exception on the next line (the call to myObject.callSomething) because the factory method failed and returned a null, and I think to myself: "Hmmm, that's weird, why didn't the assertNotNull catch that?"

And then I kick myself. Again. For making that same simple mistake another time.

No comments:

Post a Comment