Thursday, November 17, 2011

Using MSpec.Fakes–Part 1

I decided to try out MSpec.Fakes, just to see how it works and to write a very quick guide on how to use it. First, in Visual Studio 2010, I added a reference to MSpec.Fakes via NuGet:

Nuget

I chose the RhinoMocks flavour mainly as I had dabbled with both it and Moq in the past and felt that RhinoMock annoyed me less Smile (Note: I’m a TypeMock user by heart, but I often have to use an open source mocking framework, in order that all devs on the team can run the tests. TypeMock does have it’s critics, but it’s by far my choice of isolation framework, but that’s for another post.)

OK, once installed, I created a couple of nonsense classes and interfaces in order to help me get up and running:

public interface IHelper
{
    int OK(int number);
}

public class Helper : IHelper
{
    private readonly ISalaryCalculator salaryCalculator;

    public Helper(ISalaryCalculator salaryCalculator)
    {
        this.salaryCalculator = salaryCalculator;
    }

    public int OK(int number)
    {
        return this.salaryCalculator.GetValue();
    }
}

Here’s my MSpec test, I’ll explain what’s going on next:

public class when_given_a_number : WithFakes
{
    private static int result;
    private static IHelper sut;

    private Establish context = () => { sut = An<IHelper>(); };

    private Because of = () => result = sut.OK(1);

    private It should_have_been_passed_a_number = () => sut.WasToldTo(s => s.OK(Arg<int>.Is.Anything));
}

Notice that the test class inherits WithFakes, this parent class has the support for the faking implementation. The cool thing is that, regardless of the underlying mocking framework you choose to use (Moq, RhinoMock) the MSpec.Fakes API is the same. I really like this approach. Next thing to look at is how we create an instance of the Subject Under Test (SUT)

private Establish context = () => { sut = An<IHelper>(); };

The An<>(); method takes care of calling the RhinoMock equivalent of

var mockRepository = new MockRepository();
var helperMock = mockRepository.CreateMock<IHelper>();

After calling the .OK() method, the assertion for this test is that sut.OK() was called with any number:

private It should_be_1 = () => sut.WasToldTo(s => s.OK(Arg<int>.Is.Anything));

Here we see the .WasToldTo() method which takes care of verifying that .OK() was indeed called with any number. Simples.

In my next post I will show some more examples.