views:

29

answers:

2

I posted this on the TypeMock forums, but am too impatient to wait for a response there. This is a very n00b question.

I'm trying to set up a fake IContainer. Here's what I have:

var container = Isolate.Fake.Instance<IContainer>(); 
var program = Isolate.Fake.Instance<IProgram>(); 

Isolate.WhenCalled(() => container.Resolve<IProgram>()).WillReturn(program);

(IProgram is an interface in my code).

When I try to run this code, I get an Autofac exception: "The requested service MyApp.IProgram has not been registered."

How could this exception be thrown though? I'm not actually calling container.Resolve(), right? I'm just setting it up to return a fake IProgram.

Unrelated background info: I'm trialing TypeMock because Autofac uses extension methods extensively and Moq won't mock them.

+3  A: 

Hi,

A couple of things that may help - first, you can mock Resolve() calls with Moq by setting up IComponentContext.Resolve(), which all of the extension methods delegate to.

Second, Autofac is designed so that you shouldn't have to use its interfaces from your components. See for examples:

Where you need to use (and thus mock) IContainer or a similar interface, you can probably do the same thing using the Func, IIndex and/or Owned relationship types.

Hope this helps! Nick

Nicholas Blumhardt
Oh duh! I should have looked harder at my initial issue. Problem has been solved. Thanks so much Nicholas! I'm actually passing in a ContainerBuilder in one spot in my app, just to the bootstrapper and want to make sure it registers my modules correctly.
Sam Pearson
+1  A: 

Hi Sam,

Unfortunately, there's currently a bug in Isolator, which prevents faking Autofac containers. We're working to resolve it as soon as possible.

In the mean time, is there a reason you're not using Autofac as intended, meaning have it return a fake instance, such as:

[TestFixture]
public class TestClass
{
    private ContainerBuilder builder;
    private IContainer container;

    [SetUp]
    public void SetUp()
    {
        builder = new ContainerBuilder();
    }

    [Test, Isolated]
    public void Test1()
    {
        var fakeProgram = Isolate.Fake.Instance<IProgram>();

        builder.RegisterInstance(fakeProgram).As<IProgram>();
        container = builder.Build();

        var program = container.Resolve<IProgram>();

        Assert.AreEqual(fakeProgram, program);
    }
}
hmemcpy
Thanks for your answer hmemcpy! I would do this, but I'm actually faking the builder as well because it's a passed-in dependency to the bootstrapper.
Sam Pearson