模拟IoC容器? [英] Mocking an IoC Container?

查看:102
本文介绍了模拟IoC容器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

模拟IoC容器有意义吗?如果是这样,我将如何使用Moq进行处理?

Does it make sense to mock an IoC container? If so how would I go about it, using Moq?

我正在创建一个使用Unity 2.0作为IoC容器的Prism 4应用程序.我将容器注入需要其服务的类中,而不是使用Prism的ServiceLocator.对于单元测试,除非我需要其他Prism服务进行测试,否则只需实例化容器并向其注册模拟即可.我将容器传递给测试中的类,该类可以解决模拟问题.

I am creating a Prism 4 app, using Unity 2.0 as the IoC container. I inject the container into classes that need its services, rather than using Prism's ServiceLocator. For unit testing, unless I need other Prism services for my test, I simply instantiate the container and register mocks with it. I pass the container to the class under test, which resolves the mocks.

这一切都非常简单,但是我想知道是否应该模拟该容器?为什么?如果是这样,如果我使用Moq作为模拟框架,该怎么办?感谢您的帮助.

It's all fairly simple, but I am wondering if I should mock the container? Why? If so, how would I do that, if I am using Moq as my mocking framework? Thanks for your help.

推荐答案

否,模拟DI容器没有意义,因为

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

您不应只将容器注入到类中,而应只注入它们需要的服务.这也意味着您可以对它们进行单元测试,而无需完全引用DI容器.

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.

这篇关于模拟IoC容器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆