views:

34

answers:

1

I'm trying to write an automocking extension of Unity.

While it would be much easier to use a Windsor subdependency resolver and RhinoMocks I'm forced by the business to use Unity and Moq.

I haven't found an existing solution that uses Moq and I've found out why. Moq can't generate mocks from just a Type parameter, which makes Unity extensions difficult and if I try an IUnity decorator I hit a block when I get here:

public T Resolve<T>()
{
    T instance;
    try
    {
        instance = _container.Resolve<T>();
    }
    catch(ResolutionFailedException)
    {
        // if T is reference type
        instance = new Mock<T>(MockBehavior.Loose).Object;
        // else
        // return default(T);
    }
    return instance;
}

The problem is Moq's generic type constraint of being a reference type.

The question is whether the conditional logic in comments is possible in a way that will satisfy the compiler?

A: 

How about:

var type = typeof( T );
if ( type.IsInterface || type.IsClass )
{
    var mockType = typeof( Mock<> ).MakeGenericType( new[] { type } );
    var mock = (Mock) Activator.CreateInstance( mockType, MockBehavior.Loose );
    instance = (T) mock.Object;
}
else
{
    instance = default( T );
}
Mike Scott
Ah. I didn't know about MakeGenericType. That's perfect. Thanks.