如何设置对使用 jmock 的模拟调用的返回值的期望值?
How to set up expectations on the returned value of a mocked call with 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");
您应该在期望中使用 will(returnValue(...))
来指定结果,如下所示:
context.checking(new Expectations() {{
oneOf(connection).prepareStatement("test"); will(returnValue(statement));
// ...
}}
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));
}
});
我正在使用 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");
您应该在期望中使用 will(returnValue(...))
来指定结果,如下所示:
context.checking(new Expectations() {{
oneOf(connection).prepareStatement("test"); will(returnValue(statement));
// ...
}}
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));
}
});