Mock Objects

At the upcoming CLA Summit, I will be giving a presentation on mock objects. I thought I would introduce them here first for those who aren’t familiar with them. If you read any literature on unit testing you are bound to run into them.

A Different Kind of Test Double

A Mock is a type of Test Double. I wrote 2 posts recently about Test Doubles that are worth reviewing:

Just like any other Test Double a Mock Object inherits from an Interface Class and replaces the Production Class during testing. The traditional Test Doubles (Responder, Saboteur, Spy) are concerned about monitoring or manipulating indirect inputs and outputs. Mocks use a different paradigm. They verify the behavior of the Software Under Test (SUT).

A class hierarchy diagram showing various types of Test Doubles including a Mock Object.

Mocks are used to verify that the SUT uses some resource correctly. That resource could be a network connection, a database, a serial port or a piece of hardware. The Mock’s job is to record all of the methods called on the resource. It records the name of the method called and the parameters that are passed in. After the SUT has been exercised, then a verify method on the Mock Object is called to verify that the correct method calls were made. The verify method compares the actual calls against a set of desired calls.

Caution

It is important to know that there are some drawbacks to using Mock Objects. Some people may even consider them code smells. Why? Because you run the risk of overspecifying your software. When you use Mocks you are no longer treating your SUT as a black box. You are diving deep inside the internals. You may unnecessarily lock yourself into a certain implementation, and it may make refactoring very difficult. So clearly Mocks should not be overused, but using them strategically can be quite beneficial.

Learn More

If you want more information in Mocks in general, checkout the xUnit Test Patterns book (page 544). Stay tuned for the next couple blog posts where I will dive into more detail about implementing Mocks in LabVIEW. If you are in Austin for the CLA Summit be sure to check out my presentation where I introduce a Mock Object Framework for LabVIEW.

Leave a Reply

Your email address will not be published. Required fields are marked *

*