为什么模拟类这么糟糕? [英] Why is it so bad to mock classes?

查看:41
本文介绍了为什么模拟类这么糟糕?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近与一位同事讨论了关于嘲讽的问题.他说,模拟类非常糟糕,仅在少数情况下不应该这样做.

I recently discussed with a colleague about mocking. He said that mocking classes is very bad and should not be done, only in few cases.

他说只应该模拟接口,否则是架构错误.

He says that only interfaces should be mocked, otherwise it's an architecture fault.

我想知道为什么这种说法(我完全相信他)是如此正确吗?我不知道,我想被说服.

I wonder why this statement (I fully trust him) is so correct? I don't know it and would like to be convinced.

我是否错过了嘲讽的要点(是的,我阅读了马丁·福勒的文章)

Did I miss the point of mocking (yes, I read Martin Fowler's article)

推荐答案

模拟用于协议测试-它测试您将如何使用API​​,以及在使用API​​时会如何反应有相应的反应.

Mocking is used for protocol testing - it tests how you'll use an API, and how you'll react when the API reacts accordingly.

理想情况下(至少在很多情况下),应该将API指定为接口而不是类-接口定义协议,类定义实现的至少一部分.

Ideally (in many cases at least), that API should be specified as an interface rather than a class - an interface defines a protocol, a class defines at least part of an implementation.

在实践中,模拟框架在模拟类方面往往有局限性.

On a practical note, mocking frameworks tend to have limitations around mocking classes.

根据我的经验,模拟在某种程度上已经被过度使用-通常您对真正的交互并不十分感兴趣,您确实想要一个 stub ...,但是可以使用模拟框架来创建存根,并且您陷入了通过嘲笑而不是存根创建脆性测试的陷阱.虽然这很难平衡.

In my experience, mocking is somewhat overused - often you're not really interested in the exact interaction, you really want a stub... but mocking framework can be used to create stubs, and you fall into the trap of creating brittle tests by mocking instead of stubbing. It's a hard balance to get right though.

这篇关于为什么模拟类这么糟糕?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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