Search code examples
autofactypemock

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.


Solution

  • 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