Testing local objects in a method using Fake objects

I recently had a scenario where I needed to test whether calls to dependant objects were working as expected in a void method (an integration test). To do this, I constructed what is known as a Fake object, subsequently injecting this object into the constructor of my class to be tested (similar to my previous mock blog post). In my example, my fake simply delegates to the same method on the main concrete implementation, but introduce a new property into which  the result is stored (so we can perform asserts against this).

The difference between a mock and a fake is that whereas a mock sets up what will be returned from dependant objects in the test code, the fake sets this up via a new implementation of the dependant object. A good description of fakes can be found here.

(Note that stubs are different to fakes, in that they simply return hardcoded values).

Example Code

public class Foo
{
    private IDataAccessLayer dal;

    public Foo()
    {
        this.dal = new ConcreteDal();
    }

    public Foo(IDataAccessLayer dataAccessLayer)
    {
        this.dal = dataAccessLayer;
    }

    public void Bar()
    {
        // Call database to get count of something
        var count = dal.DoSomethingImportant(“SpecificGroupOrSomething”);
    }
}

public interface IDataAccessLayer
{
    int DoSomethingImportant(string key);
}

public class ConcreteDal : IDataAccessLayer
{
    public int DoSomethingImportant(string key)
    {
        // e.g. Perform a call to the database and do something complicated – 99 is dummy value
        return 99;
    }
}

public class FakeDal : IDataAccessLayer
{
    private IDataAccessLayer mainDal;

    public int ResultOfSomethingImportant { get; set; }

    public FakeDal()
    {
        this.mainDal = new ConcreteDal();
    }

    public int DoSomethingImportant(string key)
    {
        // Fake implementation of something, or in this case –
        // call main implementation and capture result
        var result = this.mainDal.DoSomethingImportant(“TestKey”);
        this.ResultOfSomethingImportant = result;
        return result;
    }
}

[TestClass]
public class FooTests
{
    [TestMethod]
    public void TestMethod1()
    {
        var fakeDal = new FakeDal();

        var foo = new Foo(fakeDal);
        foo.Bar();

        Assert.AreEqual(99, fakeDal.ResultOfSomethingImportant);
     }
}

Mocking with RhinoMocks

I have recently started getting into TDD, and have begun using mocking (specifically RhinoMocks http://ayende.com/projects/rhino-mocks.aspx). Mocking is a mechanism by which you can effectively force dependencies required by a specific piece of code to behave in a certain way, thus effectively meaning that your tests are just testing that specific piece of code (a more detailed explanation can be found here.

To allow a dependant object on a class to be mocked, an interface is normally defined for the dependant object, and an instance of this is usually made a member of the class (to ensure loose coupling). An additional constructor can then be added to to the class that allows an instance of the dependant object interface to be passed in (thus allow for a new implementation of that dependant object). This principle is known as Dependency Injection.

Note that as mocking frameworks effectively override the behaviour of a method in an object, the object being mocked must either be an interface, or have methods that are declared as virtual.

Example : Mocking Data Access

public class Foo
{
    private IDataAccessLayer dal;

    public Foo()
    {
        this.dal = new ConcreteDal();
    }

    public Foo(IDataAccessLayer dataAccessLayer)
    {
        this.dal = dataAccessLayer;
    }

    public int Bar()
    {
        // Call database to get count of something
        var count = dal.GetCountOfSomething(“SpecificGroupOrSomething”);

        // Perform a calculation (no specific reason for 12)
        var result = count * 12;

        return result;
    }
}

public interface IDataAccessLayer
{
    int GetCountOfSomething(string key);
}

public class ConcreteDal : IDataAccessLayer
{
    public int GetCountOfSomething(string key)
    {
        // Perform a call to the database and do something complicated!

        // 99 would be the count value returned from the database
        return 99;
    }
}

Performing the test

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using RhinoMocksExample1;
using Rhino.Mocks;

namespace TestProject1
{
    [TestClass]
    public class FooTests
    {
        [TestMethod]
        public void TestMethod1()
        {
            var mockRepository = new MockRepository();
            var dal = mockRepository.StrictMock(typeof(IDataAccessLayer), null) as IDataAccessLayer;
            int result;

            using (mockRepository.Record())
            {
                Expect.Call(dal.GetCountOfSomething(string.Empty)).IgnoreArguments().Return(10);
            }

            using (mockRepository.Playback())
            {
                var foo = new Foo(dal);
                result = foo.Bar();
            }

            Assert.AreEqual(120, result);
        }
    }

 

Notes:

If when referencing the Rhino.Mocks.dll, and running your tests you get an error of the form “The location of the file or directory is not trusted”, navigate to the dll in windows explorer, right click and select properties and on the general tab click the unblock button. Restart visual studio after this.

Resharper: Keymaps

I’ve just started using resharper – i tried it a few years ago and didn’t get on with it, however I really like version 4.5 (which I’m using now).

I currently use the resharper keymap, found here http://www.jetbrains.com/resharper/docs/ReSharper45DefaultKeymap2.pdf, although there are alternative keymaps (such as the visual studio default keymap) that can be found at http://www.jetbrains.com/resharper/documentation/documentation.html

Visual studio select area –alt + left mouse click + move mouse

C#: A couple of things i didn’t know

I should have know the following, but didn’t

Object Initializers:

If you have the following class:

class Person
{
  public string Forename { get; set;}
  public string Surname { get; set;}
}

Instead of initializing properties like this:

aPerson = new Person();
aPerson.Forename = “Hugh”;
aPerson.Surname = “Jazz”;

You can do this
aPerson = new Person { Forename = “Hugh”, Surname = “Jazz” };

http://msdn.microsoft.com/en-us/library/bb384062.aspx

Extension Methods (this Keyword in Method Parameters)

class Program
{
    static void Main(string[] args)
    {
        var person = new Developer { Forename = “Hugh”, Surname = “Jazz” };
        person.GreetDeveloper();
    }
}

internal interface Person
{
    string Forename { get; set; }
    string Surname { get; set; }
}

internal class Developer : Person
{
    public string Forename { get; set; }
    public string Surname { get; set; }
    public string JobTitle = “Developer”;

    public void GreetDeveloper()
    {
        this.GreetPerson(“Hello”);
    }
}

internal static class DoStuff
{
    public static void GreetPerson(this Person a, string greeting)
    {
        Console.WriteLine(string.Format(“{0} {1} {2}”, greeting, a.Forename, a.Surname));
    }
}

http://msdn.microsoft.com/en-us/library/bb383977.aspx

Overriding behaviour of methods

Below is a pattern to override the implementation of a method in a class – this is especially useful for writing unit tests, e.g. for stubbing out a method behaviour.

internal class MyClass
{
    private readonly Func<string, string> DoSomething;

    public MyClass()
    {
        this.DoSomething = DefaultImplementationOfDoSomething;
    }

    public MyClass(Func<string, string>alternateImplementationOfDoSomething)
    {
        this.DoSomething = alternateImplementationOfDoSomething;
    }

    private string DefaultImplementationOfDoSomething(string input)
    {
        return string.Format(“Your input was: {0}”, input);
    }

    public string CallMe(string input)
    {
        return this.DoSomething(input);
    }
}

We can then call our class using the normal constructor or pass through a new implementation of  DoSomething.

var myClassDefault = new AlterMethodDynamically();
Console.WriteLine(myClassDefault.CallMe(“Hello world”));

Func<string, string> newImplementation = (x) => { return string.Format(“BLAH: {0}”, x); };
var myClassMethodChanges = new AlterMethodDynamically(newImplementation);
Console.WriteLine(myClassMethodChanges.CallMe(“test”));

 

Explanation of lambda function

System.Func creates a generic delegate – you can then use a lambda function to implement to create the implementation of this delegate (as long as the signature matches what was specified by system.func).

In this example, we use the System.Func<string, string> – this specifies a delegate signature that takes one string as the input parameter and returns a string.

Func<string, string> newImplementation = (x) => { return string.Format(“BLAH: {0}”, x); };

This effectively implements the delegate a corresponds to a method:

delegate string myMethod(string x);

string newImplementation(string x)

return string.Format(“BLAH: {0}”, x);

}

Quicknote: RhinoMocks

Just a very quick and rough note – i started using RhinoMocks today, which allows you to create dummy objects when writing test code – extremely useful for simulating boundary conditions, and isolating which classes are tested. Anyway – some links…

http://ayende.com/projects/rhino-mocks.aspx

http://www.dimecasts.net/Casts/CastDetails/12 (nice intro)

Note that unit testing normally follows the pattern where you write the following:

  • SetupResult
  • Expect
  • Playback
  • Asserts