python检查是否调用了一个方法而没有嘲笑它 [英] python check if a method is called without mocking it away
问题描述
class A():
def tmp(self):
print("hi")
def b(a):
a.tmp()
要检查b中是否调用了tmp方法,推荐的方法是
To check if tmp method is called in b, the recommended way is
a = A()
a.tmp = MagicMock()
b(a)
a.tmp.assert_called()
但是这里的tmp被嘲笑了,并没有导致打印"hi"
.
But tmp here is being mocked away and is not resulting in a "hi"
getting printed.
我希望我的单元测试在不嘲笑tmp方法的情况下检查它.
I would want my unit test to check if method tmp is called without mocking it away.
这可能吗?
我知道在编写unitest时这不是标准的事情.但是我的用例(有点棘手)需要这个.
I know this is not a standard thing to expect when writing unitests. But my use case (which is bit tricky) requires this.
推荐答案
You can set the Mock.side_effect
to be the original method.
from unittest.mock import MagicMock
class A():
def tmp(self):
print("hi")
def b(a):
a.tmp()
a = A()
a.tmp = MagicMock(side_effect=a.tmp)
b(a)
a.tmp.assert_called()
当side_effect
是一个函数(在这种情况下为绑定方法,它是一种函数)时,调用Mock
也会调用具有相同参数的side_effect
.
When side_effect
is a function (or a bound method in this case, which is a kind of function), calling the Mock
will also call the side_effect
with the same arguments.
Mock()
调用将返回side_effect
返回的内容,除非它返回 Mock.return_value
代替.
The Mock()
call will return whatever the side_effect
returns, unless it returns the unnittest.mock.DEFAULT
singleton. Then it will return Mock.return_value
instead.
这篇关于python检查是否调用了一个方法而没有嘲笑它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!