Search code examples
javadateeasymock

Easymock using date expectation


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?


Solution

  • 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);
        ...
    }