Reputation: 26
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!
Upvotes: 0
Views: 822
Reputation: 108
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"
Upvotes: 4