Java News from Thursday, April 30, 2009

IBM's developerWorks has published my latest article, Easier Testing with EasyMock. Is EasyMock worth it? It does nothing that couldn't be done by manually writing mock classes, and in the case of manually written classes your project would be a dependency or two leaner. However, when mocking larger interfaces such as org.w3c.dom.Node (25 methods) or java.sql.ResultSet (139 methods and growing), EasyMock is a huge time saver that produces much shorter and more legible code at a minimal cost.

Now a word of caution: mock objects can be taken too far. It is possible to mock out so much that a test always passes even when the code is seriously broken. The more you mock, the less you're testing. Many bugs exist in dependent libraries and in the interactions between one method and the methods it calls. Mocking out dependencies can hide a lot of bugs you'd really rather find. Mocks should not be your first choice in any situation. If you can use the real dependency, do so. A mock is an inferior replacement for the real class. However, if you can't reliably and automatically test with the real class for any reason, then testing with a mock is infinitely superior to not testing at all.