0

Hello I'm trying the following test scenario

def test_main(monkeypatch):
  with patch("library.mockme.MockMe") as mock:
    message = MainObejct().message()
    assert message == "Mock me"

MainObject implementation

from library.mockme import MockMe

class MainObejct():
  def __init__(self):
    self.mock_me = MockMe()

  def message(self):
    return self.mock_me.message

The problem here is that the MockMe object is not patched... but if I change the import to from library import mockme.MockMe it actually works, is there a way to make it work with my original implementation?

Thanks!

1 Answer 1

4

Hi this is all about where and what to patch. In your example you are mocking the MockMe class in the the mockme module. You need to mock the class that is imported into your main.py module. Have a look at where to patch in the Python docs.

Hope this helps!

test_main.py

from main import MainObejct


def test_main(mocker):
    m_mockerme = mocker.patch("main.MockMe")
    m_mockerme.return_value.hello.return_value = "goodbye"
    message = MainObejct().message()
    assert message == "goodbye"

main.py

from library.mockme import MockMe


class MainObejct:
    def __init__(self):
        self.mock_me = MockMe()

    def message(self):
        return self.mock_me.hello()

library/mockme.py

class MockMe:
    def hello(self):
        return "hello"
Sign up to request clarification or add additional context in comments.

1 Comment

@AlvinEstrada if it answers your question, you should accept and upvote it, see stackoverflow.com/help/someone-answers

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.