Archive for January, 2010

January 22nd, 2010

ResultSet Mocking with JMock

by Tim Cull

I found myself recently wanting to mock out a whole mess of database interaction on a legacy system. This system didn’t have a strict data access layer, so direct calls to the database were strewn throughout the business logic.

Because JDBC is such a verbose library, mocking it out can be a challenge. For this task, I found myself with horrific-looking mock methods like this:

       private void mockSpecificPeopleQuery() throws SQLException {
		final PreparedStatement stmt = context.mock(PreparedStatement.class, "specificpeoplePreparedStatement");
		final ResultSet rs = context.mock(ResultSet.class, "specficpeopleResultSet");
		final Sequence rsSequence = context.sequence("specificpeople");
		context.checking(new Expectations() {{
			one(this.dbConnection).prepareStatement("SELECT mbid, people_id, name FROM specific_people"); will(returnValue(stmt));
			one(stmt).executeQuery(); will(returnValue(rs));
			one(rs).next(); inSequence(rsSequence); will(returnValue(true));
			one(rs).getString(1); will(returnValue("mbidCher"));
			one(rs).getInt(2); will(returnValue(2)); //"people_id" column
			one(rs).getString(3); will(returnValue("Cher")); //"name" column
			one(rs).next(); inSequence(rsSequence); will(returnValue(false));
			one(rs).close(); inSequence(rsSequence);
			one(stmt).close(); inSequence(rsSequence);
		}});

	}

I thought there had to be a better way. I remembered and was inspired by a colleague of mine (Denis) who had once nicely encapsulated all this in a helper class. So I wrote myself a simple extension to the JMock Expectations class that makes mocked-out ResultSets a whole lot easier to read, more like this: