【问题标题】:Easy Mock - How to?轻松模拟 - 如何?
【发布时间】:2015-04-07 12:29:19
【问题描述】:

我正在尝试 easyMock 测试几个类/接口方法。带有参数的方法,试图捕获参数,但得到一个或其他错误。如果我设法只记录一个期望,它甚至不会在参数管道中捕获任何内容,如果我使用以下方法,我会收到如下代码所示的错误。

@Test
public void testFireChannelInitializer() throws Exception 
{
    expect(c.pipeline()).andReturn(pipeline).times(1);
    channelListener.fireChannelInitializer(EasyMock.capture(pipe), serverHandler);
    EasyMock.replay(c, pipeline, channelListener);

    initializer.initChannel(c);

    verifyAll();
    assertEquals(4, pipe.getValues().size());
    assertTrue(pipe.getValues().get(0) instanceof LoggingHandler);
    assertTrue(pipe.getValues().get(0) instanceof ObjectEncoder);
    assertTrue(pipe.getValues().get(0) instanceof ObjectDecoder);
    assertTrue(pipe.getValues().get(0) instanceof ServerHandler);
}

导致错误

testFireChannelInitializer(com.obolus.generic.impl.DefaultChannelListenerTest) 已用时间:3.812 秒

知道什么是错的或如何使用简单的模拟?周围没有好的文档或示例。

【问题讨论】:

    标签: testing junit mocking easymock


    【解决方案1】:

    easymock 网站有一个user guide,但他们最近重新改版了他们的网站,并且该指南不像以前那么完整了。

    我认为您的问题可能是您必须进行捕获和参数匹配器。

    来自用户指南:

    匹配任何值,但在 Capture 参数中捕获它以供以后访问。您可以执行 and(someMatcher(...), capture(c)) 来从对该方法的特定调用中捕获参数。您还可以指定一个 CaptureType,告诉给定的 Capture 应该保留第一个、最后一个、全部或不保留捕获的值。

    所以你可能需要做一个and( capture(..), paramMatcher)

    此外,EasyMock 有一个烦人的 API“特性”,如果您在方法调用中使用一个参数匹配器,那么所有参数也必须包含在匹配器中,即使它是 eq()。我认为这就是你的例外所抱怨的。所以我认为这是你的两个问题。

    我不确定你的方法签名是什么样的,所以我假设它是

    void fireChannelInitializer(Object, ServerHandler);
    

    使用静态导入导入EasyMock.*

    channelListener.fireChannelInitializer( 
                    and(capture(pipe), isA(Object.class)), //captures the argument to `pipe` Capture object
                      eq(serverHandler));
    

    【讨论】:

    • 我可以用这个channelListener.fireChannelInitializer(capture(pipe), eq(serverHandler)); 进行测试。但问题是,我可以断言它只针对检查 instanceof,但它没有任何价值。
    • 您是如何创建pipe Capture 对象的?您是否尝试过使用 and() 构造?
    • 我正在像这样使用它Capture<ChannelPipeline> pipe = Capture.newInstance(CaptureType.ALL);。是的,我也尝试过使用。
    猜你喜欢
    • 1970-01-01
    • 2019-10-23
    • 1970-01-01
    • 2020-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多