Structuremap: Singleton class with multiple interfaces

In a recent project, I had the need to implement multiple interfaces in a single Repository class

public class UsageStatisticsRepository : DbContext, IApiKeyCounter, IIpAddresssCounter
{
   
// …
}

We use Structuremap as our IoC container, and attempting to configure the two interfaces as Singletons gave us two instances (naturally), once for each interface.

The solution, was to use the not-so-obvious keyword Forward in order to re-use the Singleton instance for another interface as so:

public class DigitalDiasRegistry : Registry
{
    public DigitalDiasRegistry()
    {
        For<IApiKeyCounter>().Singleton().Use<UsageStatisticsRepository>();
        Forward<IApiKeyCounter, IIpAddressValidator>();
    }
}

 

With that, the problem was solved, and only one instance occured. Since I fiddled some time to figure this out, I thought sharing it would help someone else.

Hett smilefjes

A good basis for unit testing

Over time, one developers techniques and habits that “just work”. In this post, I would like to share with you a set of base classes that I’ve been using and refining over time. They make my Unit Test writing a little more efficient and easy on the eyes.

The base of the base

I often start a new software project by setting up some form of base unit test class with functionality that I know I will be using, such as using embedded resource documents, various kinds of verifiers, test names etc. I usually name this class “BaseUnitTest”. This blog post will not be focussing on this base of bases, but to give you an idea, this is roughly how it starts out.

public class BaseUnitTest
{
    private Assembly _testAssembly;
    public EmbeddedResourceManger ResourceManager { get; internal set; }
    public IoVerificationManager IoVerifier { get; internal set; }

    public BaseUnitTest ()
    {
        _testAssembly = Assembly.GetCallingAssembly();
        ResourceManager = new EmbeddedResourceManger(_testAssembly);

        IoVerifier = new IoVerificationManager();
    }
}

I usually add on methods to this class in the form of Verfiers of different sorts. A handy base class for your Unit  Tests is not the scope of this blog though…

Wrapping AutoMocking and Instance creation with BasedOn<T>

Now follows the real nugget. A base class for your unit tests that uses StuctureMap’s AutoMocker to construct a nice, testable innstance of the class under test.

[TestClass]
public abstract class BasedOn<TInstance> : BaseUnitTest where TInstance : class
{
    public MoqAutoMocker<TInstance> AutoMocker { get; internal set; }
    public TInstance Instance { get; internal set; }

    [TestInitialize]
    public void RunBeforeEachTest() 
    {
        AutoMocker = new MoqAutoMocker<TInstance>();

        OverrideMocks();

        Instance = AutoMocker.ClassUnderTest;

        ExecuteBeforeEachTest();
    }

    public Mock<TInterface> GetMockFor<TInterface>() where TInterface : class
    {
        return Mock.Get(AutoMocker.Get<TInterface>());
    }

    /// <summary>
    /// Use this from your OverrideMocks() method so that all replacements are made before
    /// the Instance is created
    /// </summary>
    public void Replace<TInterface>(TInterface with) where TInterface: class
    {
        AutoMocker.Inject<TInterface>(with);
    }

    public virtual void OverrideMocks()
    {
    }

    public virtual void ExecuteBeforeEachTest()
    {
    }
}

How it works

The BasedOn<T> class defines an AutoMocker for the class that will be tested as well as a member named ‘Instance’ that is used in the unit tests. The method RunBeforeEachTest() is attributed with [TestInialize] so that it will execute prior to each unit test.

Note: Because this attribute is used in the baseclass, you cannot re-attribute any method in your derived unit test class. That is why there is a method named ExecuteBeforeEachTest() that you can override to accomodate your Unit testing needs.

If you need to prepare a special Mock or stub into the class you are testing, you can override the method OverrideMocks() in your unit test class – this method is executed just before the Instance member is created. The method Replace<T>(T with) is meant to be used for this very purpose.

Example of use

The class PersonManager is a business layer service that handles Person objects. In the following example, we are setting up a Unit test to ensure that person objects that do not have surnames cannot be updated. Using the BasedOn<T> base class:

[TestClass]
public class PersonManagerTests : BasedOn<PersonManager>
{
    [TestMethod]
    public void UpdatePerson_PersonHasNoLastName_DoesNotInvokeRepositoryUpdate()
    {
        // Arrange
        var testPerson = new Person();

        // Act
        Instance.UpdatePerson(testPerson);

        // Assert
        var repoMock = GetMockFor<IPersonRepository>();
        repoMock.Verify(o => o.Update(testPerson), Times.Never());
    }
}

In the next example, I am preparing the repository to throw an exception to verify
that an exception uses the logger interface:
 
[TestMethod]
public void Create_RepositoryThrowsException_ErrorMessageIsLogged()
{
    // Arrange
    var somePerson       = new Person();
    string exceptionText = "Something really bad just happened";
    var someException    = new Exception(exceptionText);
    var repoMock         = GetMockFor<IPersonRepository>();

    repoMock.Setup(o => o.Create(somePerson)).Throws(someException);

    // Act
    Instance.Create(somePerson);

    // Assert
    var loggerMock = GetMockFor<ILogger>();
    loggerMock.Verify(o => o.LogException(exceptionText), Times.Once());
}
 

The magic performed by AutoMocker combined with a relatively simple base class has helped me immensly in making my tests more readable – and for others to read! At the time of this writing, AutoMocker supports Moq, Castle, and TypeMock.

For those classes that you do not want automocked, you can always bypass the BasedOn<T> class and inherit the BaseUnitTest directly for access to the test helper methods and verifiers.

Smilefjes

Smart Reflection with dynamic type in .Net 4.0

A collegue of mine at my current project in NRK showed me how to use the dynamic keyword in C# to perform dynamic casting from a base type to a derived type. I just had to share!

The example starts with the following hierarchy of types:

public class Person{
}

public class Police : Person {
}

public class Fireman : Person{
}

The heart of the matter

Typically, you will have a controller/manager class that calls different workers based on the type of object at hand. In ASP.NET, for example, you may have a controller that will return a different rendering of a view based on the 
type of person to render. In its simplest form, the following 3 functions could form such a controller:
public void Draw(Person p) {
    Console.WriteLine("Drawing a generic person");
}

public void Draw(Police police)    {
    Console.WriteLine("Drawing the police");
}

public void Draw(Fireman fireman) {
    Console.WriteLine("Drawing a firefighter");
}
Easy peasy, you say and proceed to write some test code: 
// Arrange
var people = new List<Person>{
    new Person(),
    new Police(),
    new Fireman()
};
// Act
foreach (Person p in people)
    Draw(p);
Do you see the problem?

…the above code will issue 3 calls to the function that draws the base person type. The other two functions are never called. This is self-explanatory, since the foreach loop defines a Person reference. Using var has the same effect, because it is getting populated from a list of Person objects. The compiler simply does not see the Police or Firemen objects.

Now, if you change the foreach-loop to this:

// Act
foreach (dynamic p in people)
    Draw(p);

(use of the dynamic keyword requires that you add a reference to Microsoft.CSharp and System.Core)

The dynamic keyword is strongly typed, but, the compiler is told that the type of object, p will be determined at runtime, and not during compile time, thus each person object in the list will become a strongly typed police and fireman during runtime, similar to dynamic_cast in c++ (damned near identical if you ask me!)

Concerns

Any type of run-time-type checking will involve reflection in some form or another, however, Microsoft has gone a long way in ensuring that this is second-generation reflection, using a funky named tri-state cache to keep things fast. Another concern, of course, is that you can always cast any type to dynamic without compile-time checking, so you basically want to ensure 100% coverage by unit tests as well as ensure that the unit tests will catch type-mismatches.

Conclusion

Using the dynamic keyword will clean up the code considerably at the cost of having to keep in mind that you wil have no compile time checking of any lines of code that involve the dynamic keyword, so make sure you write those unit tests. Additionally, because this is run-time checking, you should consider other options if you depend on faster code, but for most of your code, the performance impact is non-measurable.

More on dynamic keyword here – Official documentation on MSDN

Dissecting the C# 4.0 Dynamic programming – Good article about the inner workings of dynamic