【发布时间】:2019-11-14 00:01:54
【问题描述】:
试图更多地理解 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'会背靠背打印出来,应该像这样打印:
Hello
Setting up
new style
Hello
Setting up
old style
另外,我怎样才能让它只运行一次代码,模拟值为“新测试”?
【问题讨论】:
-
我将它作为 python test.py.. 运行,它确实给出了这些结果
标签: python python-unittest python-unittest.mock