我什么时候应该嘲笑? [英] When should I mock?

查看:77
本文介绍了我什么时候应该嘲笑?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对模拟和伪造对象有基本的了解,但是我不确定我对何时/何处使用模拟有一种感觉-尤其是因为它适用于这种情况

I have a basic understanding of mock and fake objects, but I'm not sure I have a feeling about when/where to use mocking - especially as it would apply to this scenario here.

推荐答案

单元测试应通过单个方法测试单个代码路径.当某个方法的执行从该方法之外传递到另一个对象,然后又返回时,您将具有依赖项.

A unit test should test a single codepath through a single method. When the execution of a method passes outside of that method, into another object, and back again, you have a dependency.

当您使用实际的依赖关系测试该代码路径时,您不是单元测试;您正在进行集成测试.尽管这是很好且必要的,但这不是单元测试.

When you test that code path with the actual dependency, you are not unit testing; you are integration testing. While that's good and necessary, it isn't unit testing.

如果您的依赖项存在错误,则可能会以返回假阳性的方式影响您的测试.例如,您可能将依赖项传递给意外的null,并且依赖项可能不会像记录中所述那样抛出null.您的测试不会发出应有的null参数异常,并且测试通过.

If your dependency is buggy, your test may be affected in such a way to return a false positive. For instance, you may pass the dependency an unexpected null, and the dependency may not throw on null as it is documented to do. Your test does not enounter a null argument exception as it should have, and the test passes.

此外,如果不是不可能的话,您可能会发现很难可靠地使依赖对象返回在测试过程中要返回的精确值.这还包括在测试中引发预期的异常.

Also, you may find its hard, if not impossible, to reliably get the dependent object to return exactly what you want during a test. That also includes throwing expected exceptions within tests.

一个模拟代替了那个依赖.您可以设置对依赖对象的调用的期望值,设置应该给您的确切返回值,以执行所需的测试,和/或抛出什么异常,以便可以测试异常处理代码.这样,您可以轻松地测试有问题的单元.

A mock replaces that dependency. You set expectations on calls to the dependent object, set the exact return values it should give you to perform the test you want, and/or what exceptions to throw so that you can test your exception handling code. In this way you can test the unit in question easily.

TL; DR:模拟单元测试所涉及的每个依赖项.

TL;DR: Mock every dependency your unit test touches.

这篇关于我什么时候应该嘲笑?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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