Philip Frerk
Philip Frerk

Reputation: 91

Python Unit Test Mock import & check assert called with

I have a class ProductionClass with a method method_to_test which I want to test. Class ProductionClass has dependency to api, which I want to mock in the test.

from my_module.apis import api
class ProductionClass:
     def method_to_test:
         data = api.method_to_mock()
         api.method_to_check_call(data)

The test code is as follows: For api I have a mock class MockApi that I use by refering to it in the @patch decorator.

from unittest.mock import patch, MagicMock

class MockApi:
    def method_to_mock():
        return some_mock_data
    def method_to_check_call(data):
        pass

class TestClass:
    @patch('my_module.apis.api', MagicMock(return_value=MockApi()))
    def test_check_called_with(self):
         from module_of_class_production_class.ProductionClass import method_to_test
         mock_api = MockApi()
         method_to_test()
         some_data = { ... }
         mock.method_to_check_call.assert_called_with(some_data)
         

The problem is that it does not work because mock_api is not the same instance of MockApi that is provided in the @patch decorator. Is there a better way to test that?

Upvotes: 0

Views: 1244

Answers (1)

mananony
mananony

Reputation: 624

I have not tested this, but I think that your patch object will get passed as first argument to test_check_called_with like so:

@patch('my_module.apis.api', MagicMock(return_value=MockApi()))
def test_check_called_with(self, your_magic_mock):
    # Rest of code

You can also use the with construct like so:

def test_check_called_with(self):
    my_api = MockApi()
    with patch('my_module.apis.api', MagicMock(return_value=my_api)) as my_mock_api:
        # Your code here

You can checkout the official python documentation here for more details: https://docs.python.org/3/library/unittest.mock.html#quick-guide

Upvotes: 0

Related Questions