【问题标题】:Checking if an EasyMock mock is on replay mode/state检查 EasyMock 模拟是否处于重放模式/状态
【发布时间】:2012-06-29 19:12:25
【问题描述】:

是否可以确定 EasyMock 模拟是否处于重放模式?

类似:

if (EasyMock.isReplayed(mock))
  // do something

【问题讨论】:

    标签: java mocking easymock


    【解决方案1】:

    为了检查模拟的state,您需要unProxy 模拟并检查该模拟的状态集,其中一个状态是ReplayState。由于 EasyMock 与 Java 代理一起工作,这很容易:

    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;
    

    就是这样!这将打印true,因为已经设置为Replay

    也许对于 3.1 版,您可以使用:

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

    ClassExtensionHelper.getControl() javadoc

    【讨论】:

    • 我真正想确定的是,replay(mock) 方法是否被调用过。
    • 哦,我明白了...让我更正答案;)我前段时间用过!
    • 感谢您的更新。哇,这看起来真的很复杂。有没有更简单的方法?
    • 我还没有完全测试过。我想确保现有 API 中没有办法。
    • 如果您查看 EasyMock 类代码,您会发现它是一个私有方法: private static MocksControl getControl(Object mock) { ObjectMethodsFilter handler = (ObjectMethodsFilter) Proxy .getInvocationHandler(mock);返回 handler.getDelegate().getControl(); } 这或多或少是这样的:objectMethodsFilter.getDelegate().getControl()
    猜你喜欢
    • 2011-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-14
    • 1970-01-01
    • 2021-08-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多