BlackWaspTM
Testing
.NET 1.1+

NUnit Identity Assertions

The seventh part of the Automated Unit Testing tutorial continues the examination of the assertion commands provided by the NUnit framework. This article describes the identity assertions, which check the references held by objects.

Identity Asserts

The NUnit framework provides three identity assert methods. These assertions fall into two categories. Two of the methods allow you to test if a pair of objects share the same reference. The third asserts that an expected value exists within an array or collection.

In this article we will create some tests for a basic inversion of control (IoC) container. The code for the container is shown below. In this case I have made the dictionary that contains registered types public. In a real IoC container you should not do this.

public static class IoC
{
    public static Dictionary<Type, object> RegisteredTypes = new Dictionary<Type, object>();

    public static void Register<T>(T toRegister)
    {
        RegisteredTypes.Add(typeof(T), toRegister);
    }

    public static T Resolve<T>()
    {
        return (T)RegisteredTypes[typeof(T)];
    }
}

NB: The example code uses generic methods, which are not available in .NET 1.1. However, the assertions used in this article are compatible with .NET 1.1.

Assert.AreSame

The first identity assertion that we will consider is the AreSame method. This is designed for use with reference types. It compares the expected and actual objects, passed to the assert's parameters, to determine whether the two objects share the same reference. If they do, the test passes. If the references differ, even if the values of the objects are the same, the test fails.

To demonstrate, add the following test fixture to the project and run the test. This code registers an object in the IoC container, resolves the same type and checks that the registered and resolved objects are the same.

[TestFixture]
public class IoCTests
{
    object _registeredObject;

    [SetUp]
    public void SetUp()
    {
        _registeredObject = new object();
        IoC.Register<object>(_registeredObject);
    }

    [TearDown]
    public void TearDown()
    {
        IoC.RegisteredTypes.Clear();
    }

    [Test]
    public void ResolvedObjectIsRegisteredObject()
    {
        object resolved = IoC.Resolve<object>();
        Assert.AreSame(_registeredObject, resolved);
    }
}
11 April 2011