试图更多地理解 unittest.mock,但不知道为什么它运行程序两次。为简单起见,请考虑文件中的以下代码test.py
:
from unittest.mock import patch
class T():
def __init__(self):
self.setup()
def setup(self):
mock_testing = patch('test.testing').start()
mock_testing.return_value = "new testing"
def testing():
return "testing"
print("Hello")
t = T()
print("Setting up")
if testing() == "testing":
print("old style")
elif testing() == "new testing":
print("new style")
当我使用 运行脚本时python test.py
,我得到:
Hello
Hello
Setting up
new style
Setting up
old style
为什么它运行代码两次?即使它确实运行了两次,“你好”怎么会被背靠背打印出来,应该像这样打印:
Hello
Setting up
new style
Hello
Setting up
old style
另外,我怎样才能使它只运行一次代码,模拟值为“新测试”?