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

查看:90
本文介绍了如何使用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不是存根 ,它提供了比我所能提供的更权威的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.)

一开始,模拟程序似乎很乏味,但是一旦掌握了使用它们的技巧,它们就会使单元测试变得更加容易和强大.大多数语言都具有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天全站免登陆