我试图确保 Testme.command() 在 Dependency 实例上调用 bar() ,但我一直在做空。我正在使用 python -m unittest tests.test_config 运行它,并且此代码位于我项目中的 tests/test_config.py 中。
class Dependency():
def bar(self):
""" Do some expensive operation. """
return "some really expensive method"
class Testme():
def __init__(self):
self.dep = Dependency()
def command(self):
try:
self.dep.bar()
return True
except NotImplementedError:
return False
import unittest
from unittest.mock import Mock
class TestTestme(unittest.TestCase):
def test_command(self):
with (unittest.mock.patch('tests.test_config.Dependency')) as d:
d.bar.return_value = 'cheap'
t = Testme()
t.command()
d.bar.assert_called_once_with()
当我运行它时,它会失败,就像 bar() 从未被调用:AssertionError: Expected 'bar' to be called once。调用 0 次。
我应该如何测试 Testme().command() 调用 Dependency().bar()?