如何在不改变其行为的情况下检查是否调用了 @patched-out python 方法? [英] How can I check if a @patched-out python method is called, without changing its behavior?
问题描述
我一直在使用 python mock 模块为我的测试用例.我经常用 @patch('my_method')
装饰器装饰我的测试用例.然后在测试用例的主体中,我在修补的方法上设置 .return_value
属性或 .side_effect
属性以模拟其行为.同样在测试用例中,我检查修补后的方法是否使用 .assert_call_once()
调用.这工作正常.没问题.示例:
I've been using the python mock module for my test-cases. Frequently I decorate my test cases with the @patch('my_method')
decorator. Then in the body of the test-case, I set the .return_value
attribute or the .side_effect
attribute on the patched-out method to simulate its behavior. Also in the test case, I check that the patched-out method was called with .assert_called_once()
. This works fine. No problems. Example:
from mock import patch
@patch('my_method')
def test_case_1(self, mock_my_method):
mock_my_method.return_value = None
# Do some testing here
mock_my_method.assert_called_once()
现在我想做一些稍微不同的事情:我只想检查一个修补过的方法是否被调用过一次(通过使用 .assert_called_once()
.然而,我不想改变方法的行为,也不想指定一个假的返回值.我该怎么做?
Now I want to do something slightly different: I only want to check that a patched-out method was called once (by using .assert_called_once()
. However, I don't want to change the method's behavior nor do I want to specify a fake return value. How can I do that?
推荐答案
如果您只想将 patch
用于其调用记录功能,而不模拟原始函数的行为,则指定原始函数作为模拟的 side_effect
函数:
If you want to use patch
just for its call-logging functionality, without mocking out the original function's behavior, then specify the original function as the side_effect
of the mock:
@patch('my_function', side_effect=my_function)
...
side_effect
名称具有误导性.如果模拟有 side_effect
函数,调用模拟将调用 side_effect
并返回或引发 side_effect
返回或引发的任何内容.使用原始函数作为 side_effect
意味着我们得到原始函数的行为.(side_effect
可以是除了函数之外的其他几种东西,但我们在这里不需要那个功能.)
The side_effect
name is misleading. If a mock has a side_effect
function, calling the mock will call the side_effect
and return or raise whatever the side_effect
returns or raises. Using the original function as side_effect
means we get the original function's behavior. (side_effect
can be a few other kinds of thing besides functions, but we don't need that functionality here.)
这篇关于如何在不改变其行为的情况下检查是否调用了 @patched-out python 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!