单元测试、模拟对象和 ioc 的最佳实践
好吧,我最近一直在尝试进入 IoC。然而,我一直遇到一个障碍——那就是我喜欢使用模拟对象。
它们的设置快速且轻松。
但是,如果我在代码中到处使用 IoC,那么它会迫使我创建对象的测试实现(和配置),而不是使用模拟对象(即使用起订量)。
最终的结果是我得到了大量的配置文件用于测试。
此外,在测试中有很多场景,我需要在每次测试的基础上在我的类中采取不同的行为。对于最小起订量对象,这非常容易。你会如何用 IoC 来做类似的事情?
任何帮助将不胜感激。
谢谢,
麦克风
Okay so I have been trying to get into IoC lately. However, I keep running into one hurdle - that is the fact that I love using mock objects.
They are quick and painless to setup.
However, if I use IoC all over the place in my code then it forces me to create test implementations (and configurations) of my objects instead of using mock objects (ie. using moq).
The end result is that I end up with enormous configuration files for testing.
In addition there are many scenarios in testing where I require different behaviors out of my classes on a test-to-test basis. With moq objects this is extremely easy. How would you do something similar with IoC?
Any help would be much appreciated.
Thanks,
Mike
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
IoC 应该使使用模拟对象变得更容易,而不是更困难。
一些 IoC 容器框架将允许您定义要注入的预先存在的对象;使用 Moq 您只需为 myMockObject.Object 设置它。
编辑:使用模拟配置 Unity 的示例:
作为替代方案,您可以只传递模拟对象进入被测类的构造函数(用于构造函数注入)并在单元测试中完全绕过 IoC 容器。
编辑:乔什的回答是替代方案的一个很好的例子。我通常会采用他的解决方案,而不是重新配置容器。
IoC should make using mock objects easier, not harder.
Several IoC Container frameworks will allow you to define pre-existing objects to inject; with Moq you'd just set it up for myMockObject.Object.
EDIT: Example of configuring Unity with a mock:
As an alternative, you can just pass the mock object into the constructor of the class under test (for constructor injection) and bypass the IoC container entirely in your unit tests.
EDIT: Josh's answer is a good example of the alternative. I would generally go with his solution rather than reconfiguring the container.
我喜欢IoC,也喜欢一些Mock Objects...
这两者没有冲突。如果您正在进行任何类型的依赖注入,那么您只需使用您最喜欢的模拟框架创建模拟对象,然后将它们传递到您的 SUT 中。
I love IoC, and I love me some Mock Objects...
There is no conflict with these two. If you are doing any kind of Dependency Injection then you should simply have to create mock objects using your favorite mocking framework and then pass them into your SUT.