什么时候使用严格的模拟? [英] When to use strict mocks?

查看:54
本文介绍了什么时候使用严格的模拟?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试提出一种应该使用严格模拟的场景.我想不出任何.

I am trying to come up with scenario in which one should use strict mocks. I can't think of any.

你什么时候使用严格的模拟,为什么?

When do you use strict mocks and why?

推荐答案

当您想要验证是否使用正确的参数调用了预期的方法时,使用正常(或松散)模拟.

Normal (or loose) mocks are used when you want to verify that an expected method has been called with the proper parameters.

严格模拟用于验证预期的方法已被调用,而没有其他方法被调用.将它们视为一种负面测试.

Strict mocks are used to verify that only the expected methods have been called and no other. Think of them as a kind of negative test.

在大多数情况下,严格的模拟会使您的单元测试非常脆弱.即使您对内部实现进行了微小的更改,测试也会开始失败.

In most cases, having strict mocks makes your unit tests very fragile. Tests start failing even if you make a small internal implementation change.

但是让我给您举一个可能有用的示例 - 测试需求,例如:

But let me give you an example where they may be useful - testing a requirement such as:

如果数据库已经包含数据,则在缓存上获取不应该命中数据库".

"A Get on a cache should not hit the database if it already contains data".

有一些方法可以使用松散的模拟来实现这一点,但相反,简单地设置一个严格的 Mock 并具有零预期函数调用是非常方便的.对该数据库的任何调用都将引发异常并导致测试失败.

There are ways to achieve this with loose mocks, but instead, it is very convenient to simply set up a strict Mock<Database> with zero expected function calls. Any call to this database will then throw an exception and fail the test.


另一个需要使用严格模拟的场景是 AdapterWrapper 设计模式.在此模式中,您不会执行太多业务逻辑.测试这些类的主要部分是是否使用正确的参数(而不是其他参数)调用了底层函数.在这种情况下,严格的模拟工作得相当好.


Another scenario where you would want to use strict mocks is in an Adapter or Wrapper design pattern. In this pattern, you are not executing much business logic. The major part of testing these classes is whether the underlying functions have been called with the correct parameters (and no other). Strict mocks work fairly well in this case.

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

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