0

I have a method foo in Python that creates a Service class. I want to mock the Service class but when I run the test, it still attempts to instantiate the class. Here is the simplified version of my setup:

class Service:
    def __init__(self, service):
        self.service_stuff = service

    def run_service(self):
        do_service_stuff()

def foo:
    new_service = Service("bar")
    new_service.run_service()

Then my unit test:

@patch('mymodule.service_file.Service')
def test_foo(self, mock_service):
    foo()

I would like to run foo, but have it use my mocked object instead of creating an actual Service instance, but instead, when I run it, it tries to instantiate an actual instance of Service() and runs foo() as usual even though it seems to recognize the string signature I've put into patch. Why is this happening?

2 Answers 2

0

Figured it out: The patch reference to the class had to be of its imported name in the method itself rather than the original class, similar to https://stackoverflow.com/a/32461515/4234853

So the patch should look like: @patch('mymodule.foo_file.Service') instead of trying to patch the class directly.

Sign up to request clarification or add additional context in comments.

Comments

0

In this case, it might be easier to make your function more test-friendly:

def foo(cls=Service):
    new_service = cls("bar")
    new_service.run_service()

Then your test doesn't need to patch anything.

def test_foo(self):
    mock_service = Mock()
    foo(mock_service)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.