DJ180
DJ180

Reputation: 19854

EasyMock: Times behaviour not being checked for strict mock

My unit test contains a "strict" mock of my DAO. My mocking behaviour is common to all tests apart from the @Test below. Therefore, I have added this common mocking behaviour within the @Before method. The specialist mocking behaviour is then added to the @Test itself:

@Before
public void setUp() {
    reset(myDAO);
    expect(myDAO.findMyObjects(code, myID)).andReturn(myObjects).times(1);
    expect(myDAO.findMyObjects(myID)).andReturn(myObjects).times(1);
    replay(myDAO);
}

@Test
public void testMyFirstMethod() {
    reset(myDAO);
    expect(myDAO.findMyObjects(myID)).andReturn(new ArrayList<MyObject>()).times(200);
    replay(myDAO);

    Set<OtherObject> otherObjects = myTestClass.myTestMethod(null, myID);
    assertEquals("Empty set is returned", 0, otherObjects.size());
}

I have checked that the .times(1) behaviour is validated in my other unit tests. However, in the above test the .times(200) behaviour is not validated (as my unit test only invokes this once). Why is this?

Upvotes: 0

Views: 1137

Answers (1)

Louis Wasserman
Louis Wasserman

Reputation: 198053

You need to use EasyMock.verify(myDAO) to tell EasyMock that the replay is done and that the expectations should now be satisfied.

When you call myTestMethod only once, EasyMock doesn't know that it has to check myDAO before the method finishes, so it waits for more calls, and then the method returns successfully without EasyMock noticing that findMyObjects wasn't called enough times.

As for why the times(1) behavior is getting validated, I'm not sure, but I suspect that the verification might be triggered by other tests.

That said, your @Before method organization is really off. You're setting expectations, starting a replay, resetting, and then replaying again?

Upvotes: 3

Related Questions