Thursday, September 20, 2007

Pop Quiz : JUnit Negative Testing

When will this fail?

public class NegativeTest extends TestCase{

public void testCalendar() {

try {

Calendar now = Calendar.getInstance();

for(int i = 0 ; i < 10000000; i++) ;

if(! now.before(Calendar.getInstance()))
throw new RuntimeException();

fail("Negative test failure");

}catch(Throwable t) { }

}

}

11 comments:

Anonymous said...

Always! Except when something weird happens and time starts running backwards... (or there is a bug in the Calendar implementation)

Not Dennis Byrne said...

Nope. Try again!

Anonymous said...

Ha!
I never fails, because the call to "fail()" throws an AssertionError which is caught and ignored in the try-catch-clause.
... even if time starts running backwards :)

Nice trap! :)

Not Dennis Byrne said...

I award you one cool point for giving the correct answer!

You are right. Calling fail will not fail the test if the Error thrown by fail() is caught. This is why it is important to always catch Exception, rather than Throwable. This is also a good reason to always start w/ a failing test.

Anonymous said...

Thank you, oh enlightened one.
I have learned something today. :)

Not Dennis Byrne said...

I am sensing some sarcasm in you. Have we ever worked together?

Anonymous said...

You're a Java MAVEN!

Not Dennis Byrne said...

I should have guessed it was you. Shithead.

Anonymous said...

Actually I'm not the "Shithead" you suspect.
And I apologize for the perceived sarcasm. It was meant it in the true sense of the words. Just wanted to give it a lighter tone.

My website is winterfish.de if you'd like to know my identity.

Not Dennis Byrne said...

no need to apologize anonymous. I found just found out who the other poster was. cheers.

name said...

Magnific!