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?

Asked By: Sha

||

Answers:

monkeypatch couldn’t work for me. I used @patch or with patch functions.

Answered By: Sha

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
Answered By: Macintosh_89
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.