我有以下的项目结构:
root/
|-mylib/
|-tests/
| |-__init__.py
| |-test_trend.py
|-__init__.py
|-data.py
|-trend.py
在
trend.py
中:from mylib.data import get_item
def get_trend(input: str):
item = get_item(input)
return f"Trend is: {item}"
在 data.py
中:
def get_item(id):
print("ORIGINAL")
return get_item_from_db(id)
测试
我想要对get_trend
进行单元测试,因此我在test_trend.py
中对get_item
进行了补丁操作:
import unittest
from unittest.mock import patch
from mylib.trend import get_trend
def p__get_item(input):
return 0
class MyTestCase(unittest.TestCase):
@patch("mylib.data.get_item", new=p__get_item)
def test_trend(self):
v = get_trend()
self.assertEqual(v, "Trend is: 0")
但是当我运行测试时(该命令在root
目录内运行):
python -m unittest discover
我看到日志显示原始的
get_item
被调用了。 当然测试失败了。我做错了什么?
尝试1
如果我尝试使用patch
API的其他版本
class MyTestCase(unittest.TestCase):
@patch("mylib.data.get_item")
def test_trend(self, mocked_fun):
mocked_fun.return_value = 0
v = get_trend()
self.assertEqual(v, "Trend is: 0")
它仍然不能正常工作。在控制台日志中,我可以看到打印了ORIGINAL
并且测试失败。
实验1
如果我将@patch
中的target
更改为不存在的属性,如:
@patch("mylib.data.non_existing", new=p__get_item)
实际上,我从库中得到了一个错误,说该模块不包含这样的属性。因此,看起来mylib.data.get_item
已经被正确地定位,但补丁仍未生效。
get_stuff
。但实际上,你的测试测试的是一个模拟对象,并没有什么帮助。 - Klaus D.new_callable
而不是new
? - LearningNoob