3 回答

TA贡献1868条经验 获得超4个赞
您需要修补正在测试的模块中的符号“A”,即“B”。
当你这样做时@mock.patch("full.path.A")
,它应该是:
@mock.patch("full.path.to.B.A")
现在A
模块中的符号B
用你的模拟打了补丁。

TA贡献1998条经验 获得超6个赞
你不是错过了文件本身的名称吗?
@mock.patch( 'namespacename.mylibname.stats_collector.mylibname_stats_collector.StatsCollector')

TA贡献1852条经验 获得超1个赞
当我写这篇文章时,你可能已经想通了。
经验法则:不要在定义类或函数的地方打补丁,而是在使用它们的地方打补丁。
a.py
class A:
def exponent(self, a, b)
return a ** b
b.py
from a import A
class B:
def add_constat(a, b, c)
return A().exponent(a, b) + c
为了测试 add_constant 方法,您可能会想像这样修补 A
TestB:
@patch('a.A.exponent', mock_a)
test_add_constant(self, mock_a)
这是错误的,因为您正在修补给出定义的文件中的类。
A 在类 B 的文件 b 中使用。因此,您应该修补该类。
TestB:
@patch('b.A')
test_add_constant(self, mock_a):
# mock_a is fake class of A, the return_value of mock_a gives us an instance (object) of the class(A)
instance_a = mock_a.return_value #
# we now have instance of the class i.e A, hence it is possible to call the methods of class A
instance_a.exponent.return_value = 16
assert 26 = B().add_constant(2,4,10)
我对您的代码进行了一些修改,以便它可以在我的 Python 环境中使用。
stats_collector.py
class StatsCollector:
def __init__(self, user_id, app_id):
self.user_id = user_id
self.app_id = app_id
def stat(self):
return self.user_id + ':' + self.app_id
mydb.py
from stats_collector import StatsCollector
import logging
class Db:
# constructor
def __init__(self, db_name):
self.db_name = db_name
def begin_transaction(self, user_id, app_id):
logging.info("Begin")
stat = StatsCollector(user_id, app_id).stat()
if stat:
return user_id + ':' + app_id
return "wrong User"
使用类似的比喻:为了测试文件 mydb.py 的 Db 类中的“begin_transaction”,您需要修补 mydb.py 文件中使用的 StatsCollector 类
test_mydb.py
from unittest.mock import patch
from unittest import TestCase
class TestDb(TestCase):
@patch('mydb.StatsCollector')
def test_begin_transaction(self, db_class_mock):
# db_class_mock is the mock of the class, it is not an instance of the DB class.
# to create an instance of the class, you need to call return_value
db_instance = db_class_mock.return_value
db_instance.stat.return_value = 1
# i prefere to do the above two lines in just one line as
#db_class_mock.return_value.stat.return_value = 1
db = Db('stat')
expected = db.begin_transaction('Addis', 'Abeba')
assert expected == 'Addis' + ':' + 'Abeba'
# set the return value of stat method
db_class_mock.return_value.stat.return_value = 0
expected = db.begin_transaction('Addis', 'Abeba')
assert expected == "wrong User"
我希望这可以帮助网络中的某人
添加回答
举报