1 回答

TA貢獻(xiàn)1998條經(jīng)驗(yàn) 獲得超6個(gè)贊
為什么代碼不起作用
通常,您會收到 0 次調(diào)用,因?yàn)槟难b飾器不會調(diào)用_p.func1.
您不必編寫,mocked.get_p因?yàn)槟呀?jīng)偽造了它,因此您的mocked參數(shù)代表mod.get_p函數(shù)。
另外,您不應(yīng)該重新定義mocked變量,因?yàn)樗呀?jīng)是mock.Mock
如果mod1你有錯(cuò)誤,你的deco裝飾器是錯(cuò)誤的,我建議你閱讀更多關(guān)于 python 裝飾器的內(nèi)容。
適用于您的案例的工作代碼
mod1.py
class P:
def func1(self):
pass
_p = None
def get_p():
global _p
if _p is None:
_p = P()
return _p
# other code omitted, it's a decorator which will call _p.func1 once
def deco(func):
def wrapper(*args, **kwargs):
p = get_p()
p.func1()
return func(*args, **kwargs)
return wrapper
test_mod1.py
import unittest
from unittest import mock
import mod1
class TestFunc1(unittest.TestCase):
@mock.patch('mod1.get_p')
def test_1(self, mocked):
_p_mock = mock.Mock()
mocked.return_value = _p_mock
@mod1.deco
def test():
pass
test()
_p_mock.func1.assert_called_once()
if __name__ == '__main__':
unittest.main()
在 openSUSE Tumbleweed、Python3.8.5 上運(yùn)行:
> python test_mod1.py
.
----------------------------------------------------------------------
Ran 1 test in 0.001s
OK
添加回答
舉報(bào)