如何在单元测试中模拟另一个模块中的方法

问题描述 投票:0回答:1

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

但是这无法模拟该功能。

django python-3.x mocking python-mock django-unittest
1个回答
1
投票

您应该在导入的文件中模拟它。例如,您已经在create_t_customer中声明了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}
© www.soinside.com 2019 - 2024. All rights reserved.