views:

236

answers:

3

I am currently using JUnit 4.4 and Java 1.6.x. And after a recent code fix, we started getting this AssertionFailedError in my JUnit tests on the method:

UtilityTest.testParseDate(4t): Mon Jan 15 09:26:07 PST 2001 expected: "Mon Jan 15 09:26:07 PST 2001" but was: "Mon Jan 15 09:26:07 PST 2001"

junit.framework.AssertionFailedError: UtilityTest.testParseDate(4t): Mon Jan 15 09:26:07 PST 2001 expected: but was: at UtilityTest.testParseDate(Unknown Source)

As you can see, the expected and actual appear identical, and after several code inspections, we can find no obvious error in the code. Test runs with actual data have also produced correct (expected) results.

Has anyone seen this behavior before in JUnit, and if so, did you find the cause and/or a fix?

I have seen the same thing in previous versions of Java and JUnit myself: always somewhat random when it occurs, and usually the only fix "that worked" was to retype the chunk of code in from scratch. Weird, yet that was tne only way to remove this error. I'm trying to find out something more "concrete" in the behavior this time.

Thanks,

-Richard

+2  A: 

Can you post the code for UtilityTest.testParseDate()?

Are you using assertEquals() on the date values or are you comparing them in another fashion? If so, can you assert that the millisecond timestamps are equal instead of the dates themselves?

Kevin
Thanks for poking my brain to think about the milliseconds!
Huntrods
+1  A: 

The test code is:

Calendar cal = Calendar.getInstance();
Date today = new Date();
cal.set(2001, 0, 15, 9, 26, 07);  // Jan 15 2001, 09:26:07
// format 4 = ddd mmm dd hh:mm:ss TTT yyyy (with gettime)
assertEquals("UtilityTest.testParseDate(4t): Mon Jan 15 09:26:07 PST 2001", cal.getTime(),  Utility.parseDate("Mon Jan 15 09:26:07 PST 2001", today, true));

Here's what parseDate looks like (just the method signature as the code was long):

public static Date parseDate(String date, Date today, boolean gettime) {

I think you may have it though - even though it does not DISPLAY the milliseconds, they would be different.

Cheers,

-Richard

Huntrods
That would probably explain the apparent "randomness" of the test case passing and failing. Sometimes the instructions will happen in less than a millisecond, in which case your test will work.
Kevin
A: 

That was it - the milliseconds were off. A judicious application of "cal.clear()" fixed the problem.

Cheers,

-Richard

Huntrods