【发布时间】: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 = [ ... ]
有没有可能实现这个想法?
【问题讨论】:
-
请说明您的问题是关于 pytest 还是 unittest。
标签: python unit-testing mocking pytest python-unittest