我正在测试一个python类。我想嘲笑一些类的方法,但不是所有的方法。使用mock.patch
可以很好地实现这一点。我的问题是:
有什么干净的解决办法吗?在
为了提供更多的颜色,下面是一个例子:
# test_me.py
class ClassUnderTest:
# All foo functions should be mocked
def foo1(self):
pass
def foo2(self):
pass
def foo3(self):
pass
# All bar functions should NOT be mocked
def bar1(self):
pass
def bar2(self):
pass
def bar3(self):
pass
# test.py
@mock.patch.object(test_me.ClassUnderTest, 'foo3', autospec=True)
@mock.patch.object(test_me.ClassUnderTest, 'foo2', autospec=True)
@mock.patch.object(test_me.ClassUnderTest, 'foo1', autospec=True)
class MyTestCase(unittest.TestCase):
def setup_mocks(self, mock_foo1, mock_foo2, mock_foo3):
# Do things like assign side_effect or return_value to each of the foo mocks
pass
def test_1(self, mock_foo1, mock_foo2, mock_foo3):
self.setup_mocks(mock_foo1, mock_foo2, mock_foo3)
# Do test_1 tests
def test_2(self, mock_foo1, mock_foo2, mock_foo3):
self.setup_mocks(mock_foo1, mock_foo2, mock_foo3)
# Do test_2 tests
我需要模仿的类和函数越多,这个解决方案就越不干净。有更好的解决办法吗?在
我已经准备好接受这样的回答:“你需要重构你的代码,使之更易于测试”。我习惯于从C/C++世界中设计测试到体系结构。然而,我希望从一个动态的语言更好。我已经使用python很长一段时间了,但从来没有深入研究过mocking。在
有一件事可能会对您有所帮助,那就是在setup方法中去掉undertest类。在
相关问题 更多 >
编程相关推荐