Python Test Monkeypatch with Arguments
Question:
I try to create a mock test with monkeypatch. I have a typical service-repository class.
repository_class.py
find_by_id(id):
con.select(....);
service_class.py
get_details(id):
some pre-process...
item = repository_class.find_by_id(id)
post-process...
return result
then I try to create a mock test with mocking repository method under service:
def test_bid_on_brand_keyword(monkeypatch):
mock_data = "abc"
monkeypatch.setattr(repository_class, 'find_by_id', mock_data)
ans = service_class.get_details(id)
assert ans is not None
This doesn’t work. It tries to call real repository method. Any suggestion?
Answers:
monkeypatch
couldn’t work for me. I used @patch
or with patch
functions.
Return value should be an (mock) object, so i would do it like this
def test_bid_on_brand_keyword(monkeypatch):
monkeypatch.setattr(repository_class, 'find_by_id', lambda _:"abc")
ans = service_class.get_details(id)
assert ans is not None
I try to create a mock test with monkeypatch. I have a typical service-repository class.
repository_class.py
find_by_id(id):
con.select(....);
service_class.py
get_details(id):
some pre-process...
item = repository_class.find_by_id(id)
post-process...
return result
then I try to create a mock test with mocking repository method under service:
def test_bid_on_brand_keyword(monkeypatch):
mock_data = "abc"
monkeypatch.setattr(repository_class, 'find_by_id', mock_data)
ans = service_class.get_details(id)
assert ans is not None
This doesn’t work. It tries to call real repository method. Any suggestion?
monkeypatch
couldn’t work for me. I used @patch
or with patch
functions.
Return value should be an (mock) object, so i would do it like this
def test_bid_on_brand_keyword(monkeypatch):
monkeypatch.setattr(repository_class, 'find_by_id', lambda _:"abc")
ans = service_class.get_details(id)
assert ans is not None