模拟和猴子修补有什么区别?

What is the difference between mocking and monkey patching?

我和 python 一起工作,我对测试有点陌生。我经常看到用本地方法替换外部依赖的测试,如下所示:

import some_module

def get_file_data():
  return "here is the pretend file data"

some_module.get_file_data = get_file_data

# proceed to test

我看到这在 question 中被称为“猴子补丁”。我还看到“模拟”这个词与“猴子修补”一起使用了很多,或者在看起来非常相似的场景中使用了很多。

这两个概念有区别吗?

Monkey patching 正在运行时用另一个替换 function/method/class,用于测试目的、修复错误或以其他方式改变行为。

unittest.mock library 利用猴子补丁来用模拟对象替换部分被测软件。它提供了编写巧妙的单元测试的功能,例如:

  • 它记录了模拟对象是如何被调用的,所以你可以测试 使用断言的代码调用行为。
  • 一个方便的装饰器 patch() 用于实际的猴子修补。
  • 您可以将模拟对象设为 return 特定值 (return_value),引发特定异常 (side_effect)。
  • 模仿'magic methds'(例如__str__)。

例如,您可以使用模拟来替换客户端中的网络 I/O(urllib、请求),因此单元测试无需依赖外部服务器即可工作。