
.NET 3.5+Mocking Property Expectations with Moq
Moq provides similar capabilities when mocking properties of classes or interfaces as when mocking methods. Although the same verification and expectation set up methods can be used in some circumstances, there are additional options for properties.
Testing Properties
When you are creating unit tests you should isolate the unit being tested from its dependencies. When you choose to use mock objects for this purpose, you will often need to mock properties. This may involve verifying that properties are read or changed and adding expectations to either the get or set accessors. In this article we will see how this is possible using the Moq isolation framework.
To demonstrate the use of mocked properties we need a class to be tested that has a dependency. The type below fulfils our requirements. This class provides members that allow the control of a traffic light system, including performing a test of the light bulbs. The ITrafficLights dependency represents an object that allows the individual red, amber and green light bulbs to be illuminated. This is an over-simplistic implementation but is sufficient to demonstrate the mocking we need.
public class LightController
{
ITrafficLights _lights;
public LightController(ITrafficLights lights)
{
_lights = lights;
}
public void SetGo()
{
_lights.Green = true;
_lights.Red = _lights.Amber = false;
}
public void SetStop()
{
_lights.Red = true;
_lights.Green = _lights.Amber = false;
}
public void SetPrepareToGo()
{
_lights.Red = _lights.Amber = true;
_lights.Green = false;
}
public void SetPrepareToStop()
{
_lights.Amber = true;
_lights.Red = _lights.Green = false;
}
public bool BulbsOK()
{
return !_lights.BulbFailure;
}
}
The ITrafficLights interface is shown below. This has three write-only properties that are used to change the state of the bulbs and a read-only property that returns true when a bulb failure is detected.
public interface ITrafficLights
{
bool Red { set; }
bool Amber { set; }
bool Green { set; }
bool BulbFailure { get; }
}
The example code will use NUnit for the testing framework and Moq for the isolation framework. Add references to nunit.framework.dll and Moq.dll if you are recreating the code. You should also add the following using directives in the code files that will contain the tests.
using NUnit.Framework;
using Moq;
19 October 2011