开发者

Setting up behavior on a method appears to be calling the method

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.


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:

  • http://nblumhardt.com/2010/01/the-relationship-zoo/
  • http://code.google.com/p/autofac/wiki/TypedNamedAndKeyedServices and
  • http://code.google.com/p/autofac/wiki/DelegateFactories

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


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);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜