Unit Testing with mock objects

adam

The main reason for using mock objects to write unit tests is so that they are unit tests. Without mock implementations, unit tests quickly become integration tests. There is nothing wrong with integration tests however they tend to make coverage data inaccurate, since code which is exercised incidentally rather than being directly tested gets marked as covered, and they can end up slowing down the test suite since these types of tests usually involve having to load the complete application context in a Spring application or they require a container and a JNDI instance for other J2EE apps.

My motto is keep it simple. I don’t like to think too much, particularly about my tests. When I see a red bar I don’t want to have to wonder whether it is the method under test which is broken or if it is one of its dependencies. I like to be certain that it is the method under test. It greatly reduces the time it takes me to get the green bar of goodness back.

I, personally, use EasyMock as my mock framework of choice. Combined with Unitils it takes a great deal of drudgery out of mocking out dependencies. Using the Unitils EasyMock annotations you can mark an interface as a mock using @Mock and mark the class under test which will have the mocks injected using @TestedObject. This doesn’t seem to work on classes using constructor injection, however it works fine for setter injection and means there is no need to manually setup your mocks and inject them into the class under test.

Complete details on how to use these annotations can be found here


Leave a Reply