首页 > 解决方案 > 如何在单元测试期间模拟另一个模块内的方法

问题描述

在我的一个测试用例中,流程要求客户提供流程,其中调用转到 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}

但这无法模拟该功能。

标签: djangopython-3.xmockingpython-mockdjango-unittest

解决方案


您应该在它导入的文件中模拟它。例如,您已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}

推荐阅读