django - 如何在单元测试期间模拟另一个模块内的方法
问题描述
在我的一个测试用例中,流程要求客户提供流程,其中调用转到 api.py 文件,其中的响应是从函数 create_t_customer 保存的,如下所示:
在 api.py 文件中,它使用从文件 customer.py 导入的方法 create_t_customer
response = create_t_customer(**data)
在 customer.py 文件中,函数的代码是
def create_t_customer(**kwargs):
t_customer_response = Customer().create(**kwargs)
return t_customer_response
我想在单元测试中模拟函数 create_t_customer。当前我尝试了以下方法,但似乎没有用
class CustomerTest(APITestCase):
@mock.patch("apps.dine.customer.create_t_customer")
def setUp(self,mock_customer_id):
mock_customer_id.return_value = {"customer":1}
但这无法模拟该功能。
解决方案
您应该在它导入的文件中模拟它。例如,您已create_t_customer
在 in中声明customer.py
并使用它api.py
。你应该模拟它api
而不是customer
像这样的模块。
class CustomerTest(APITestCase):
@mock.patch("x.y.api.create_t_customer")
def test_xyz(self, mock_customer_id):
mock_customer_id.return_value = {"customer":1}
推荐阅读
- python-2.7 - ImportError:无法导入名称_remove_dead_weakref python 2.7
- android - 重启手机后音乐播放列表不见了,这是奥利奥的问题吗?
- javascript - 从 xml(字符串)制作数组的优雅方式
- reactjs - 按下按钮时如何阅读道具反应原生
- java - SQLite 创建表
- eclipse - 谷歌云 SDK
- c++ - QComboBox ListView 正在占用组合框框架
- javascript - 节点(错误:dlopen 失败:找不到符号)
- java - Java-Spark-Drools:线程“main”中的异常 java.lang.RuntimeException:找不到默认的 KieBase
- django - Froala 在 django 中无法正常工作