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) { }
}
}
Thursday, September 20, 2007
Pop Quiz : JUnit Negative Testing
When will this fail?
Subscribe to:
Post Comments (Atom)
11 comments:
Always! Except when something weird happens and time starts running backwards... (or there is a bug in the Calendar implementation)
Nope. Try again!
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! :)
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.
Thank you, oh enlightened one.
I have learned something today. :)
I am sensing some sarcasm in you. Have we ever worked together?
You're a Java MAVEN!
I should have guessed it was you. Shithead.
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.
no need to apologize anonymous. I found just found out who the other poster was. cheers.
Magnific!
Post a Comment