接口如何使单元测试和模拟更容易? [英] How do interfaces make unit testing and mocking easier?
问题描述
经常有人说接口使模拟和单元测试变得更容易.界面对此有何帮助?
It is often said that interfaces make mocking and unit testing an easier process. How do interfaces help with this?
推荐答案
提供许多实现,从而启用模拟功能是接口的本质.
尤其是在集成测试中,您可以提供您的依赖系统模型的版本(例如网络服务). 您可以提供最简单的界面实现,而不是实际调用从属系统甚至模块,或者复杂且难以实例化的类型将提供单元测试正确完成所需的结果.
Especially in integration testing you are able to give your version of a dependency system mock-up (e.g. a web-service). Instead of actually calling a dependent system or even a module, or a complicated and difficult to instantiate type, you can provide a simplest interface implementation that will provide results needed for the unit test to complete correctly.
此外,在单元测试中使用时,实际上是一个依赖类型(称为BigGraph),在其后面隐藏了复杂的对象模型,实际上做集成测试而不是单元测试. 如果任何依赖类型(BigGraph)中有错误,而不是您要测试的类型,那么您的测试就很容易中断.使用实体模型可以降低发生这种情况的风险.
In addition to that, when you use in unit testing, an actual dependent type (call it BigGraph) hiding a complicated object model behind it, you are in fact do integration testing not unit testing. Your test can easily break if there is a bug in any of the dependent types (BigGraph), not the type you're testing, thus not unit-testing. Using mock-ups reduce risk of that happening.
我已经看到许多持续集成系统显示出一个错误的数十个错误,它们应该显示一个或最多两个错误,所有这些都是由于对象模型太复杂以及单元测试编写不正确-不使用模拟-ups.
I've seen many continuous integration systems showing dozens of errors for one bug, when they should show up one, or at most a couple, all because of too complicated object models, and incorrectly written unit-test - not using mock-ups.
今天的模拟框架比过去更加复杂(字节码修改等),因此有时并不总是需要接口甚至是虚拟方法,但是无精打采的接口使它们成为可能.
Today mocking frameworks are more sophisticated (bytecode modification, etc.) than the old days, so sometimes interfaces or even virtual methods aren't always needed, but nerveless interfaces enable them.
接口将无济于事;然后实现/模拟所有这些都是很痛苦的.
这篇关于接口如何使单元测试和模拟更容易?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!