Pergunta

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.

Foi útil?

Solução

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

Outras dicas

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);
    }
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top