我想在测试中将一个类替换为另一个类,并检查其方法是否被调用。
我想做的事情的一个例子。
class A:
def some_method(self):
print("A")
class B:
def some_method(self):
print("B")
def some_function():
a = A()
a.some_method()
def test_some_function():
with patch("__main__.A", new=B) as mocked_a:
some_function()
assert mocked_a.some_method.called_once()
如何正确做?
在您提供的代码中,您尝试使用unittest.mock库用新的B类修补A类,然后检查是否调用了some_method。但是,您的代码中存在一些问题,包括补丁上下文管理器的错误使用。在这个更正的代码中,我们使用补丁上下文管理器将类 A 替换为类 B 并模拟打印函数。然后,我们检查是否使用字符串“B”调用 print 函数,该字符串是 B 类的 some_method 的输出。 这是我的解决方案
from unittest.mock import patch, MagicMock
class A:
def some_method(self):
print("A")
class B:
def some_method(self):
print("B")
def some_function():
a = A()
a.some_method()
def test_some_function():
with patch("__main__.A", new=B):
with patch("__main__.print") as mock_print:
some_function()
mock_print.assert_called_with("B")
if __name__ == "__main__":
test_some_function()