0

When refactoring some old unit tests, I added a verify() call to see how many times a method was being expected and was surprised to see that the "expected" calls was greater than what was set using times(). For some reason the expect call on the next line is being added to my method.

Why is this happening?

Test Class

public class SandBoxTest {    
    @Test
    public void shouldGetSand() {
        Sand niceMock = EasyMock.createNiceMock(Sand.class);

        EasyMock.expect(niceMock.sandMethod()).andReturn(1).times(2);
        EasyMock.expect(Box.boxMethod()).andReturn(99).times(11);

        EasyMock.replay(niceMock);

        EasyMock.verify(niceMock);
    }
}

Output When Run

java.lang.AssertionError: 
  Expectation failure on verify:
    Sand.sandMethod(): expected: 13, actual: 0

Output That Was Expected

java.lang.AssertionError: 
  Expectation failure on verify:
    Sand.sandMethod(): expected: 2, actual: 0

Details: EasyMock v3.1

Followup: Opened feature request with EasyMock. https://jira.codehaus.org/browse/EASYMOCK-128

Rylander
  • 19,449
  • 25
  • 93
  • 144

1 Answers1

1

So here's what's up.

The javadoc for expect() states

expect(T value) Returns the expectation setter for the last expected invocation in the current thread.

With these calls

EasyMock.expect(niceMock.sandMethod()).andReturn(1).times(2);
EasyMock.expect(Box.boxMethod()).andReturn(99).times(11);

The last expected invocation is, in both cases, niceMock.sandMethod() since it's the only Mock method call, so it adds 2+11 = 13.

EasyMock's mocked object have some counter in the proxy that registers what was called.

Box.boxMethod() is just a static method call. You can't mock that. Or maybe you can.

Community
  • 1
  • 1
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • That is weird. I can believe that is what is happening, but I that javadoc is... not easily understood. Also I would have expected that EasyMock would throw an exception on the expect call to a static method. – Rylander Oct 03 '13 at 21:00
  • @Mike Try calling a static method that has a different return type. – Sotirios Delimanolis Oct 03 '13 at 21:01
  • `java.lang.IllegalStateException: incompatible return value type` Still would prefer an except along the lines of "can not mock static methods" – Rylander Oct 03 '13 at 21:03
  • @MikeRylander I'm assuming your static method had same return type as your `sandMethod()` so the last expected can be returned. And I agree with you, it's not clear. – Sotirios Delimanolis Oct 03 '13 at 21:04