在Python中,我们想要断言一个函数在调用另一个函数时被调用。但是,我们希望在调用所需函数后忽略执行。当我们不知道函数的其余部分时,这种必要性就会出现。稍后将开发的其余功能可能会从外部环境(例如数据库网关)调用对象。典型的解决方案是模拟该对象。然而,当我们练习 TDD 时,我们可能还没有弄清楚函数的其余部分。因此,我们需要忽略它。 这是我要开发的功能:
class A:
def func(self):
self.a()
self.b() # the rest of the function that we do not develop yet and we want to ignore during the test because actually, we do not even know if there is actually a b function.`
测试功能
def test_a_is_called_during_func():
mocked_a = Mock()
with patch("A.a", new= mocked_a):
A().func()
mocked_a.assert_called_once()
我们需要在测试中添加一些内容来忽略
b()
,这可以改进我们的测试设计,并使其独立,如果我们向函数添加一些内容,则无需返回此测试。
实现此目的的一种方法是让方法
a
的模拟版本抛出您创建的一些自定义异常。然后,func
的执行不会超出对a
的调用,您可以在测试中捕获异常。例如:
class AbortTestedFunctionException(Exception):
pass
def test_a_is_called_during_func():
mocked_a = Mock(side_effect=AbortTestedFunctionException())
with patch("A.a", new=mocked_a):
try:
A().func()
except AbortTestedFunctionException:
pass
mocked_a.assert_called_once()
这并不是万无一失的:如果
func
使用 try... except Exception
执行全面的异常处理策略,它就不会按预期工作。