Stubbing Dependencies

Consider the following class. The class is nice because it has all it has has a single dependency which is injected in the constructor and it is an interfaces which gives us the ability to work with at least Dependency-inversion and interface segregation principles from the SOLID principles.

public class SalaryManager
{
    private readonly IEmployeStorage _storage;

    public SalaryManager(IEmployeStorage storage)
    {
        _storage = storage;
        eventRaiser.eventToRaise += OnUpdate;
    }

    public double[] GetSaleries(params String[] employes)
    {
        var outSal = new double[employes.Length];

        for (int i = 0; i < employes.Length; i++)
        {
            outSal[i] = _storage.RetrieveCurrentSalery(employes[i]).Salery;
        }

        return outSal;
    }
}

To get this class under test, create a new unit test project in Visual Studio and derive the test from TestTarget<T> where T would be the class under test, namely, SalaryManager

[TestClass]
public class Basics : TestTarget<SalaryManager>
{
    [TestMethod]
    public void SetUpDependencyBehaviour()
    {
        Given.That<ITaxationCalulator>(x => x.CalculateTax(0)).Returns(200d);

        double salery = When.Calling.RaiseSalery("foo");

        Assert.AreEqual(200, salery);
    }
}

The test method specifies that the dependency of type ITaxationCalculator must return the value of 200 double. The next line invokes the method RaiseSalery("foo") on the test target using the When.Calling syntax. The result of this call is stored in the salery variable which is then asserted to be of the value 200 in the Assert on the last line.

What Happened

The line When.Calling initialized a new instance of SaleryManager. TestByWire detected that in order to be constructed an instance of a class implementing the ITaxationCalculator interface had to be passed to the constructor. TestByWire automatically created a stub to which behavior can be applied.

The Given.That instructor specifies that the stub of the interface ITaxationManager must return 200 when called. Please not that parameter values are ignored.

Last edited Jun 8, 2011 at 6:54 PM by RasmusTherkelsen, version 4

Comments

No comments yet.