views:

104

answers:

1

I'm trying to mock an Autofac resolve, such as

using System;
using Autofac;
using TypeMock.ArrangeActAssert;

class Program
{
    static void Main(string[] args)
    {
        var inst = Isolate.Fake.Instance<IContainer>();
        Isolate.Fake.StaticMethods(typeof(ResolutionExtensions), Members.ReturnNulls);
        Isolate.WhenCalled(() => inst.Resolve<IRubber>()).WillReturn(new BubbleGum());
        Console.Out.WriteLine(inst.Resolve<IRubber>());
    }
}

public interface IRubber
{}

public class BubbleGum : IRubber
{}

Coming from Moq, the syntax and exceptions from TypeMock confuse me a great deal. Having initially run this in a TestMethod, I kept getting an exception resembling "WhenCalled cannot be run without a complementing behavior". I tried defining behaviors for everyone and their mothers, but to no avail.

Then I debug stepped through the test run, and saw that an actual exception was fired from Autofac: IRubber has not been registered.

So it's obvious that the static Resolve function isn't being faked, and I can't get it to be faked, no matter how I go about hooking it up.

Isolate.WhenCalled(() => ResolutionExtensions.Resolve<IRubber>(null)).WillReturn(new BubbleGum());

... throws an exception from Autofac complaining that the IComponentContext cannot be null. Feeding it the presumably faked IContainer (or faking an IComponentContext instead) gets me back to the "IRubber not registered" error.

+1  A: 

This might be one of those cases of swimming against the tide - the amount of code required to create a 'real' container, with the appropriate dependency registered, is less or similar to the configuration for TypeMock. I'd suggest going down that path.

Instead of having the target component depend on IContainer at all, you could instead use 'Relationship Types' like Func, which are implicitly supported by Autofac and more expressive, in addition to being easily mockable. http://nblumhardt.com/2010/01/the-relationship-zoo/ has more information on that approach, as does http://code.google.com/p/autofac/wiki/DelegateFactories.

Cheers, Nick

Nicholas Blumhardt