Mock Objects

Writing simple unit tests is easy (especially with Eclipse). What if your class uses outside resources, such as JDBC connections? You don't want to have a real database connection. That takes too long to setup and is too cumbersome to write quick tests with.

Mock Objects (a good implementation is found at (WORST website in the world)) handles this situation reall well. It allows you to write tests against code that use otherwise heavy weight or expensive dependencies.

Mock Objects are two things. They are implementations of common interfaces, like java.sql.* or This allows them to slip right in where the regular implementations would.

Mock Objects also are programmable. In your tests you instruct (or, for those of us in the biz, you "program") the mock object what to expect and how it will be interacted with. It's best to illustrate this.

Here is a snippet from a unit test that checks JDBC code.

MockConnection2 connection = new MockConnection2();
MockPreparedStatement ps = new MockPreparedStatement();
connection.setupAddPreparedStatement(query, ps);
ps.addExpectedSetParameter(1, "seth");

... doStuff(connection); ...


The setupAddPreparedStatement call tells our mock connection to /expect/ a certain query. The test will fail if that query is not issued. The addExpectedSetParameter call tells the mock prepared statement to expect a single param of value "seth". If the prepared statement gets anything else, the test will fail. Calling verify() will do those checks.

As you can see, this is different from normal unit testing. In normal unit testing, we usually do some work, collect a return value, and then check it with some assertions. With this mock object code, we do most of the work in preparing the code for testing.

This is a very lightweight and quick way to test your code that relies on dependencies. You'll find that has implementations for many j2se and j2ee classes.
Post a Comment

Popular posts from this blog

I ported a JavaScript app to Dart. Here's what I learned.

Converting Array to List in Scala

Minification is not enough, you need tree shaking