views:

149

answers:

1

The EasyMock documentation is pretty clear that

The behavior for the three object methods equals(), hashCode() and toString() cannot be changed for Mock Objects created with EasyMock, even if they are part of the interface for which the Mock Object is created.

The code that I'm trying to test uses equals() to compare my mock object to something else. I'd like to do something like

expect(mock.equals(obj)).andReturn(false);

When I do that, I get an IllegalStateException. No surprise there, given what the documentation says.

Does anyone have any suggestions for an alternate approach? Is there another way to control what the mock object will return when equals() is called on it? I suppose that I can create a subclass that overrides equals()

class FooImplOverrideEquals extends FooImpl {
    public boolean equals;
    public boolean equals(Object obj) { return equals; }
}
FooImplOverrideEquals mock = createMock(FooImplOverrideEquals.class);
mock.equals = false; // instead of expect(mock.equals(obj)).andReturn(false);

but this seems inelegant. I feel like I'm missing something important (like the reason why EasyMock doesn't let you override those object methods). Is there a better solution?

+2  A: 

Many of the mocking libraries don't support this because it's generally a bad idea. If you're doing an equals() comparison then you have a value object, not a real collaborator and you're better off using a real instance. If you're using equals() to represent some other concept (isBestFriendsWith(other)), then you can stub that if appropriate.

Steve Freeman
In the particular case that spawned my question, I ended up using a real instance instead of a mock. Your explanation about value objects vs. collaborators makes a lot of sense and that's probably what was in the back of my mind, even though I hadn't consciously identified those two roles.
Ed Wagner