Checking if an EasyMock mock is on replay mode/state

easymock, java, mocking

Solution

In order to check the `state` of a mock you need to unProxy your mock and check the state set for that mock, and one state is the `ReplayState`. As EasyMock works with Java Proxies, this is quite easy:

EasyMock.replay(mock); // setting replay state to a mock object

// stripping proxy and getting the invocation handler
InvocationHandler invocationHandler = Proxy.getInvocationHandler(mock); 


// for easyMock, invocation handler holds the state of the mock 
ObjectMethodsFilter objectMethodsFilter = (ObjectMethodsFilter) invocationHandler; 

// not the not so elegant part:
// this: objectMethodsFilter.getDelegate().getControl().getState() 
// retrieves  the state instance that can be checked if it is an 
// instance of ReplayState.class
boolean inReplayState = objectMethodsFilter.getDelegate()
    .getControl().getState() instanceof ReplayState;

And thats it! This will print `true` because was already set to `Replay`

Maybe for version 3.1 you could use:

ClassExtensionHelper.getControl(mock).getState() instanceof ReplayState

`ClassExtensionHelper.getControl()` javadoc

Problem

Is it possible to determine if an EasyMock mock is on replay mode? Something like: ``` if (EasyMock.isReplayed(mock)) // do something ```

Original source