【问题标题】:How to mock a method inside another module during unit testing如何在单元测试期间模拟另一个模块内的方法
【发布时间】:2019-11-19 07:21:41
【问题描述】:

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

    您应该在它导入的文件中模拟它。例如,您在customer.py 中声明了create_t_customer,并在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}
    

    【讨论】:

      猜你喜欢
      • 2022-01-23
      • 2018-06-16
      • 1970-01-01
      • 1970-01-01
      • 2014-04-16
      • 2015-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多