Mocks 是如何使用的? [英] How are Mocks meant to be used?

查看:11
本文介绍了Mocks 是如何使用的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我最初被介绍给 Mocks 时,我觉得主要目的是模拟来自外部数据源的对象.这样我就不必维护一个自动化的单元测试测试数据库,我可以伪造它.

When I originally was introduced to Mocks I felt the primary purpose was to mock up objects that come from external sources of data. This way I did not have to maintain an automated unit testing test database, I could just fake it.

但现在我开始有了不同的想法.我想知道 Mocks 是否更有效地用于将测试方法与其外部的任何东西完全隔离开来.不断浮现在脑海中的图像是您绘画时使用的背景.你想防止油漆弄脏所有东西.我只是在测试那个方法,我只想知道它对这些伪造的外部因素有何反应?

But now I am starting to think of it differently. I am wondering if Mocks are more effective used to completely isolate the tested method from anything outside of itself. The image that keeps coming to mind is the backdrop you use when painting. You want to keep the paint from getting all over everything. I am only testing that method, and I only want to know how it reacts to these faked up external factors?

这样做似乎非常乏味,但我看到的优势是当测试失败时,这是因为它被搞砸了,而不是 16 层.但是现在我必须进行 16 次测试才能获得相同的测试覆盖率,因为每个部分都将单独测试.此外,每个测试都变得更加复杂,并且与它正在测试的方法联系更紧密.

It seems incredibly tedious to do it this way but the advantage I am seeing is when the test fails it is because it is screwed up and not 16 layers down. But now I have to have 16 tests to get the same testing coverage because each piece would be tested in isolation. Plus each test becomes more complicated and more deeply tied to the method it is testing.

这对我来说是正确的,但它也似乎很残酷,所以我有点想知道其他人的想法.

It feels right to me but it also seems brutal so I kind of want to know what others think.

推荐答案

推荐你看看 Martin Fowler 的文章 Mocks Aren't Stubs 对 Mocks 的处理比我能给你的更权威.

I recommend you take a look at Martin Fowler's article Mocks Aren't Stubs for a more authoritative treatment of Mocks than I can give you.

模拟的目的是在隔离依赖项的情况下对代码进行单元测试,这样您就可以真正在单元"级别测试一段代码.被测试的代码是真正的交易,它依赖的每一段代码(通过参数或依赖注入等)都是一个模拟"(一个空的实现,当它的一个方法被调用时总是返回预期值.)

The purpose of mocks is to unit test your code in isolation of dependencies so you can truly test a piece of code at the "unit" level. The code under test is the real deal, and every other piece of code it relies on (via parameters or dependency injection, etc) is a "Mock" (an empty implementation that always returns expected values when one of its methods is called.)

Mocks 一开始可能看起来很乏味,但是一旦你掌握了使用它们的窍门,它们就会使单元测试变得更加容易和健壮.大多数语言都有 Mock 库,这使得模拟相对微不足道.如果您使用 Java,我会推荐我个人最喜欢的:EasyMock.

Mocks may seem tedious at first, but they make Unit Testing far easier and more robust once you get the hang of using them. Most languages have Mock libraries which make mocking relatively trivial. If you are using Java, I'll recommend my personal favorite: EasyMock.

让我结束这个想法:您也需要集成测试,但是拥有大量的单元测试可以帮助您找出哪个组件包含错误,何时存在.

Let me finish with this thought: you need integration tests too, but having a good volume of unit tests helps you find out which component contains a bug, when one exists.

这篇关于Mocks 是如何使用的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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