Saurabh_Jhingan
Saurabh_Jhingan

Reputation: 320

How to mock a method inside another module during unit testing

In one of my test case the flow requires that a customer provision process wherein the call goes to the api.py file where in the response is saved from the function create_t_customer like following:

In api.py file it is using the method create_t_customer imported from file customer.py

response = create_t_customer(**data)

In customer.py file the code for function is

def create_t_customer(**kwargs):
    t_customer_response = Customer().create(**kwargs)
    return t_customer_response

I want to mock the function create_t_customer inside the unittest. Current I have tried the following but it doesn't seem to be working

class CustomerTest(APITestCase):
    @mock.patch("apps.dine.customer.create_t_customer")
    def setUp(self,mock_customer_id):
        mock_customer_id.return_value = {"customer":1}

But this is not able to mock the function.

Upvotes: 0

Views: 1639

Answers (1)

Nafees Anwar
Nafees Anwar

Reputation: 6608

You should mock it inside the file it is imported. For example you have declared create_t_customer in customer.py and using it in api.py. You should mock it from api instead of customer module like this.

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}

Upvotes: 3

Related Questions