views:

192

answers:

3

Hi, I'm mocking a method with easymock that has a date in its body, something like this:

public void testedMethod() {
    ...
    if (doSomething(new Date())) {
    ...
}

And my test looks like this:

public void testThatMethod() {
    ...
    expect(testedClass.testedMethod(new Date())).andReturn(false);
    ...
}

But when I run the test sometimes I get an error like this:

Unexpected method call testedMethod(Thu Jan 28 09:45:13 GMT-03:00 2010): testedMethod(Thu Jan 28 09:45:13 GMT-03:00 2010): expected: 1, actual: 0

I think that it's because sometimes the date has a slightly difference. I've tried the some flexible expectations without success. Is there a way to get around this?

+2  A: 

If you can figure out exactly why it's failing, you can write your own matcher to be more flexible in matching the date. See the section on matchers http://easymock.org/EasyMock2_2_Documentation.html

Jeff Storey
+2  A: 

It could be that the millisecond part of the dates are different. You probably need to zero that using Calendar.set() before you create the date object:

Calendar myCalendar = Calendar.getInstance();
myCalendar.set(Calendar.MILLISECOND, 0);
Date testDate = myCalendar.getTime();

But that is a guess :)

Rich
+1  A: 

Stop using new Date(), use a Calendar with constant time instead.

//Declare the Calendar in your test method
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(0l);

//receive the calendar to be used in testedClass constructor
public void testedMethod() {
    ...
    if (doSomething(cal.getTime())) {
    ...
}

//use the same calendar to make the assertion
public void testThatMethod() {
    ...
    expect(testedClass.(testedMethod(cal.getTime())).andReturn(false);
    ...
}
Kalecser