【问题标题】:pytest: setup a mock for every test functionpytest:为每个测试函数设置一个模拟
【发布时间】:2019-02-28 10:54:16
【问题描述】:

为 Python 项目创建单元测试,我们遇到了这种“模板”

from unittest import TestCase
from unittest.mock import patch, Mock

@patch('......dependency1')
@patch('......dependency2')
@patch('......dependencyn')
class MyTest(TestCase):

  def test_1(self, mock1, mock2, mockn):
      # setup mock1 & mock2...
      # call the subject case 1
      # assert response and/or interactions with mock1 and mock2...

  def test_2(self, mock1, mock2, mockn):
      # setup mock1 & mock2...
      # call the subject case 2
      # assert response and/or interactions with mock1 and mock2...

重点是,有时“设置”部分会在某些测试用例中重复,所以我想将配置提取到setUp() 方法中,例如,以下是伪代码:

def setUp(self):
  mock1.foo.return_value = 'xxx'
  mock2.goo.side_effect = [ ... ]

def test_1(self, mock1, mock2, mockn):
  # default setup is perfect for this test

def test_2(self, mock1, mock2, mockn):
  # this time I need...
  mock2.goo.side_effect = [ ... ]

有没有可能实现这个想法?

【问题讨论】:

标签: python unit-testing mocking pytest python-unittest


【解决方案1】:

pytestunittest 都提供了您所询问的可能性,并且对于这两个功能都在各自的文档中通过示例进行了解释:在 pytest 文档中查找 fixture,在文档中查找 setup unittest 文档。

但是,在实践中使用这些功能很快就会失控,并且容易产生不可读的测试代码。它有两种形式,一种是共享夹具设置变得太大(太笼统),使读者难以理解与特定测试用例实际相关的内容。第二个是,测试代码不再是自包含的,似乎魔法发生在外面。 Meszaros 将产生的测试气味称为“Obscure Test”,上述场景称为“General Fixture”和“Mystery Guest”。

我的建议是,更喜欢从每个测试中显式调用的辅助函数/方法。您可以拥有其中的几个,给它们起描述性的名称,从而使您的测试代码保持可读性,而无需阅读器首先搜索文件以查找任何“自动”的东西。在您的示例中,测试可能如下所示:

def test_1(self, mock1, mock2, mockn):
  default_setup(mock1, mock2, mockn)
  # further test code...

def test_2(self, mock1, mock2, mockn):
  default_setup(mock1, mock2, mockn)
  setup_mock2_to_behave_as_xxx(mock2)
  # further test code...

def test_3(self, mock1, mock2, mockn):
  setup_mock1_to_always_xxx(mock1)
  setup_mock2_to_behave_as_xxx(mock2)
  setup_mockn_to_xxx(mockn)
  # further test code...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-01
    • 2018-08-06
    • 2017-09-21
    • 2021-08-22
    • 2018-06-07
    • 1970-01-01
    相关资源
    最近更新 更多