为什么模拟课程如此糟糕? [英] Why is it so bad to mock classes?

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

问题描述

我最近与一位同事讨论了模拟.他说,mocking classes 很糟糕,不应该做,只有在少数情况下.

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.

我是否错过了嘲笑的重点(是的,我阅读了 Martin Fowler 的文章)

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

推荐答案

Mocking 用于 protocol 测试 - 它测试您将如何使用 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.

根据我的经验,mocking 有点被过度使用 - 通常你对确切的交互并不真正感兴趣,你真的想要一个 stub...但是mocking 框架可用于创建存根,并且你陷入了通过模拟而不是存根来创建脆弱测试的陷阱.不过,要做到正确的平衡是很困难的.

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天全站免登陆