如何使用jmock设置对模拟调用的返回值的期望?

时间:2015-11-25 12:43:59

标签: java jdbc mocking jmock

我正在使用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");

1 个答案:

答案 0 :(得分:2)

您应该在期望中使用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));
    }
});
相关问题