【发布时间】:2014-08-29 02:58:00
【问题描述】:
在 python 中是否有任何等效的严格模拟?一些报告意外调用模拟方法的机制(本例中为 action.step2()),就像 GoogleMock 框架中的这种情况。
class Action:
def step1(self, arg):
return False
def step2(self, arg):
return False
def algorithm(action):
action.step1('111')
action.step2('222')
return True
class TestAlgorithm(unittest.TestCase):
def test_algorithm(self):
actionMock = mock.create_autospec(Action)
self.assertTrue(algorithm(actionMock))
actionMock.step1.assert_called_once_with('111')
【问题讨论】:
-
您使用哪个版本的 Python?看来您的代码可以使用 Python 3 中的
unittest.mock按原样工作。 -
您的意思是“未明确设置的任何呼叫”是“意外呼叫”吗?
-
@Cilyan 抱歉不准确。此示例使用 python 2.7.6 进行测试。但是我在 python 3.4.0 中得到了相同的行为,其中 unittest 在标准库中。
-
@J0HN 是的。当方法被调用,但没有人在测试体中预测时,该方法将被调用。在这种情况下,StrictMock (GoogleMock) 将使测试失败。
标签: python unit-testing mocking python-mock