Search code examples
javajdbcmockingjmock

How to set up expectations on the returned value of a mocked call with jmock?


I'm using jmock to run some tests. I'd like to ensure that a third-party library will correctly call the following sequence on the JDBC API:

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

The connection object is created as such:

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

How do I create the statement object? I've tried these, neither worked:

// 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");

Solution

  • You should use will(returnValue(...)) in your expectations to specify the result, like this:

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

    See also the JMock cheat sheet.

    Example that 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));
        }
    });