在 unittest `setUp` 中部分模拟一个方法

Partially mock a method in unittest `setUp`

我正在尝试了解 mock/patch 框架,但遇到了问题。这是我的简化代码:

file_a.py
class A:
  def f(self): 
    b = B()
    b.g()
    b.h()

file_b.py
class B:
  def g(self):
    return network_requests(...)

  def h(self):
    return "This is should not be mocked."

file_test.py
class SomeTests:
  def setUp(self):
    with patch('file_b.B', autospec=True) as mock:
      mock.g.return_value = "Mocked value"
      mock.side_effect = lambda : B()
    self.a = A()

  def test(self):
    self.a.f()

基本上我只想在测试中模拟 B.g,而不是 B.h。我从 https://docs.python.org/3/library/unittest.mock-examples.html#partial-mocking 那里得到了一些想法,但是 B.g 仍然没有被嘲笑。

谢谢!

在您链接的示例中,关键问题是

Unfortunately datetime.date is written in C

这就是为什么你需要模拟模块并包装你不想模拟的东西(你不能直接修补 C 方法)。

是否所有其他情况(补丁 python 对象)都可以使用:

with patch('file_b.B.g', autospec=True) as mock_g:
  mock_g.return_value = "Mocked value"

无论如何请注意,您的补丁将仅在 with 上下文中处于活动状态,您将在其中找到原始参考。为了更好地控制上下文,您还可以使用装饰器 start()stop().

强烈建议您仔细阅读patch and where to patch