Home > Software engineering >  Revisited: Python Mocking a function from an imported module
Revisited: Python Mocking a function from an imported module

Time:12-04

Python 3.9.
In my unittest, I want to instantiate ServiceProvider, but it has to use mock_get_service in the test, not the imported get_service, since this makes network calls.

I have worked through many solutions, including the original named above, with no success. Every time, the original get_service is called and crashes.

app_module:

from services import get_service

class ServiceProvider()

    def find_service(self, service_id):
        return get_service(service_id)

unittest_module:

from app_module import ServiceProvider

def mock_get_service(service_id):
    """ Test method: return the named service. """
    if service_id == 'ServiceA':
        service = ServiceA()
    else:
        service = ServiceB()
    return service

class Test_ServiceProvider(unittest.TestCase):
    def test1_find_service(self):
        with patch('app_module.get_service') as mocked_get_service:
            mocked_get_service.side_effect = mock_get_service
            server = ServiceProvider()
            serv = server.find_service('ServiceA')
            self.assertIsInstance(serv, ServiceA)

CodePudding user response:

You should use patch.object when mocking a member of an object.

with patch.object(ServiceProvider, "get_service", side_effect=mock_get_service):
    # your test case will use mock_get_service() when ServiceProvider.get_service() is called

CodePudding user response:

from app_module import ServiceProvider

def mock_get_service(service_id):
    """ Test method: return the named service. """
    if service_id == 'ServiceA':
        service = ServiceA()
    else:
        service = ServiceB()
    return service

class Test_ServiceProvider(unittest.TestCase):
    def test1_find_service(self):
        with patch.object(ServiceProvider, "get_service", side_effect=mock_get_service):

            mocked_get_service.side_effect = mock_get_service
            server = ServiceProvider()
            serv = server.find_service('ServiceA')
            self.assertIsInstance(serv, ServiceA)
  • Related