我在尝试模拟调用另一个类的类时遇到问题。 我有三个模块:
树.py
from branch import Branch
class Tree:
type_of_tree = None
branches = None
def __init__(self, type_of_tree, branches = 0, default_leaves = 0):
self.type_of_tree = type_of_tree
self.branches = []
for branch in range(branches):
self.create_branch(default_leaves)
def create_branch(self, leaves):
self.branches.append(Branch(leaves))
def get_leaves(self):
return_value = []
for branch in self.branches:
return_value.extend(branch.get_leaves())
return return_value
分支.py
import uuid
from leave import Leave
class Branch:
leaves = None
identifier = None
def __init__(self, leaves=0):
self.identifier = str(uuid.uuid4())
self.leaves = []
for leave in range(leaves):
self.create_leave()
def create_leave(self):
self.leaves.append(Leave())
def get_leaves(self):
return_value = []
for leave in self.leaves:
return_value.append(leave.get_identifier())
return return_value
离开.py
import uuid
class Leave:
identifier = None
def __init__(self):
self.identifier = str(uuid.uuid4())
def get_identifier(self):
return self.identifier
我正在尝试用以下代码模拟离开课程:
from unittest.mock import patch, MagicMock
from uuid import uuid4
from tree import Tree
FAKE_UUID = str(uuid4())
class TestLeave:
def test_leave(self):
with patch('leave.Leave') as mock_leave:
mock_leave.return_value = MagicMock()
mock_leave.get_identifier.return_value = FAKE_UUID
tree = Tree("Pine", 1, 1)
leaves = tree.get_leaves()
assert leaves == [FAKE_UUID]
测试失败。我一直在阅读补丁文档但我没有找到相关信息。
我发现我的错误阅读:https://docs.python.org/3.12/library/unittest.mock.html#where-to-patch
模拟休假类的正确方法是从分支导入的类:
from unittest.mock import patch
from uuid import uuid4
from tree import Tree
FAKE_UUID = str(uuid4())
class TestLeave:
def test_leave(self):
with patch('branch.Leave') as mock_leave:
mock_leave.return_value.get_identifier.return_value = FAKE_UUID
tree = Tree("Pine", 1, 1)
leaves = tree.get_leaves()
assert leaves == [FAKE_UUID]
在此示例中,测试工作正常。注意你需要使用mock_leave.return_value获取对象,然后使用get_identifier.return_value = FAKE_UUID模拟返回值