为什么我的单元测试需要一个模拟框架? [英] Why do I need a mocking framework for my unittests?

查看:17
本文介绍了为什么我的单元测试需要一个模拟框架?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,围绕 .NET 世界中所有不同的模拟框架进行了相当大的宣传.我还没有完全理解他们的伟大之处.编写我自己需要的模拟对象似乎并不难.尤其是在 Visual Studio 的帮助下,我可以快速编写一个实现我想要模拟的接口的类(它为我自动生成几乎所有内容),然后为我的测试所需的方法编写一个实现.完毕!为什么要为了节省几行代码而费尽心思去理解一个模拟框架.还是一个模拟框架不仅仅是为了节省代码行数?

Recently there has been quite some hype around all the different mocking frameworks in the .NET world. I still haven't quite grasped what is so great about them. It doesn't seem to be to hard to write the mocking objects I need myself. Especially with the help of Visual Studio I quickly can write a class that implements the interface I want to mock (it auto-generates almost everything for me) and then write an implementation for the method(s) I need for my test. Done! Why going through the hassle of understanding a mocking framework for the sole purpose of saving a few lines of code. Or is a mocking framework not only about saving lines of code?

推荐答案

当我终于掌握了模拟对象的窍门后,我意识到它们对于单元测试至关重要,原因与双盲测试或控制组必不可少对于科学试验:它们隔离了您实际测试的内容.

Once I finally got the hang of mock objects, I realized that they're essential for unit testing for the same reason that double blind testing or control groups are essential for scientific trials: they isolate what you're actually testing.

如果您正在测试一个通过其他接口进行大量交互的类,您不仅可以节省模拟每个接口的代码行,而且您还可以获得执行诸如抛出如果调用了意外的方法则异常"或如果这些方法被乱序调用则异常".您可以使用模拟框架变得非常复杂,尽管我很快承认学习曲线很长,但当您加快速度时,它们将有助于使您的单元测试更加彻底而不会臃肿.

If you're testing a class which has quite a bit of interaction via other interfaces, you not only save the lines of code on having to mock each and every interface, but you also gain the ability to do things like "throw an exception if an unexpected method is called" or "exception if these methods are called out of order". You can get remarkably sophisticated with mock frameworks, and though I'll quickly admit there's a large learning curve, when you get up to speed they'll help make your unit tests more thorough without being bloated.

这篇关于为什么我的单元测试需要一个模拟框架?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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