【问题标题】:How to set up expectations on the returned value of a mocked call with jmock?如何使用 jmock 设置对模拟调用的返回值的期望?
【发布时间】:2015-11-25 21:47:45
【问题描述】:

我正在使用 jmock 运行一些测试。我想确保第三方库在 JDBC API 上正确调用以下序列:

context.checking(new Expectations() {{
    oneOf(connection).prepareStatement("test");
    oneOf(statement).setFetchSize(10);
    oneOf(statement).executeQuery();
}});

connection 对象是这样创建的:

Mockery context = new Mockery();
connection = context.mock(Connection.class);

如何创建statement 对象?这些我都试过了,都不管用:

// This creates an independent PreparedStatement mock, not the one that will be returned
// by the Connection.prepareStatement call
PreparedStatement statement = context.mock(PreparedStatement.class);

// This doesn't return a mock object, which I can pass to the oneOf() method.
PreparedStatement statement = oneOf(connection).prepareStatement("test");

【问题讨论】:

    标签: java jdbc mocking jmock


    【解决方案1】:

    您应该在期望中使用will(returnValue(...)) 来指定结果,如下所示:

    context.checking(new Expectations() {{
        oneOf(connection).prepareStatement("test"); will(returnValue(statement));
        // ...
    }}
    

    另请参阅JMock cheat sheet

    例如I use in tests of Jaybird:

    final PooledConnectionHandler conHandler = context.mock(PooledConnectionHandler.class);
    final Statement statement = context.mock(Statement.class);
    final Connection connectionProxy = context.mock(Connection.class);
    final StatementHandler handler = new StatementHandler(conHandler, statement);
    
    context.checking(new Expectations() {
        {
            oneOf(conHandler).getProxy(); will(returnValue(connectionProxy));
        }
    });
    

    【讨论】:

    • 哈,一开始我没听懂,这个断开连接的will(...) DSL 元素有一些魔力...谢谢!
    • @lukaseder 是的,在这方面,mockito 感觉更自然一些。尽管根据我的经验,每个模拟框架都有自己的优点和缺点。本质上,期望中的每个方法调用都会推入额外的状态。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多