Tags: mockobject testing
Mock objects is a technique for unit testing an object by replacing the objects it interacts with with mocks. If we are unit testing User and it needs an Address object, we create a mock object that implements the Address interface and give that to the User.
A Mock object has to implement the appropriate interface, but none of the behaviour. Before being used we tell it what method calls to expect and after using it we call an extra method on it (usually called 'verify()') which checks all its calls were correct.
By surrounding an object with mocks we effectively isolate it from the rest of the application and test its interactions, like an electronics engineer plugging a component into a test bed.
In order to be able to replace the objects an object uses by mocks we need the InversionOfControl principle which is helped a lot by TellDontAsk.
When an object deals with an external API / library, there is a temptation to mock objects of that library. Instead of doing this heed the Don't Mock Objects You Don't Own principle. Wrap all access to that outside library with a thin adapter. For example pass all your calls to Java's JDBC through a Database interface - then you will only need to mock your Database.
See: http://www.mockobjects.com
Last published: Monday 31st October 2011
<<Previous Next>>