Mocking an IoC Container?

二次信任 提交于 2019-12-01 10:52:15
Mark Seemann

No, it doesn't make sense to mock a DI container because application classes should not reference a container at all.

Instead of injecting the container into the classes, you should inject only the services that they need. This will also mean that you can unit test them without referencing a DI container at all.

I agree with Mark Seemann's answer generally for 99% of classes this works fine.

There are some factory type classes (perhaps classes that take a Model and convert it to a ViewModel where those ViewModels have dependencies) for which this doesn't work. In these cases, I generally accept the interface for the container, rather than its concrete type (IUnityContainer, in your case) and mock as usual.

public class MyWidgetFactory : IMyWidgetFactory
{
     public MyWidgetFactory(IUnityContainer container)
     {
          //...
     }
     public Widget[] GetWidgets()
     {
         //...
     }
}

public class MyWidgetFactoryConsumer
{
     private Widget[] _widgets;
     public MyWidgetFactoryConsumer(IMyWidgetFactory factory)
     {
          _widgets = factory.GetWidgets();
     }
}

Both of the above classes are testable, with the factory class needing to have a mocked version of the IUnityContainer and the consumer needing only the factory itself mocked.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!