Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using autofac with moq

Tags:

c#

moq

autofac

I need to register my Autofac container with specific interface, for this case I want to resolved mock.

How can I do it?

I've tried:

var AppContainer = ApplicationContainer.GetApplicationContainer();  
var cb = new ContainerBuilder();
cb.RegisterType<Mock<IStudyLoader>>().As<IStudyLoader>().SingleInstance();
cb.Update(AppContainer);

I don't want to change my code to resolve something else than IStudyLoader, but Mock<IStudyLoader> is not substitutable for IStudyLoader; e.g Mock<IStudyLoader>.Object is substitutable for IStudyLoader, but I cant register Mock<IStudyLoader>.Object because it not a type.

Correct me please; I have the feeling that I am missing something.

(I have another restriction, I can't use other container than ApplicationContainer.GetApplicationContainer())

(I think it's better to manually inject the dependency when testing, but I don't want to change the production code this time.)

like image 558
Delashmate Avatar asked Nov 09 '11 07:11

Delashmate


1 Answers

I found the solution, Yes it is possible!

  var AppContainer = ApplicationContainer.GetApplicationContainer();
  var studyLoaderMock = new Mock<IStudyLoader>().Object;
  cb.RegisterInstance(studyLoaderMock).As<IStudyLoader>();
  cb.Update(AppContainer);
like image 77
Delashmate Avatar answered Oct 05 '22 00:10

Delashmate