I've recently started learning how to use mock from unittest library and encountered a problem figuring out how to correctly mock class dependencies.
Below is the example i'm trying to mock
client.py
class HttpClient:
def request(self, method, url, params = None):
if method == "GET":
return requests.get(url)
elif method == "POST":
return requests.post(url, body=params)
Here I inject the HttpClient object into the Post class
As I understood I need to mock self.client.request and this can be replaces with requests get or maybe in some other way?
data.py
class Post:
def __init__(self, client: HttpClient):
self.client = client
self.base_url = "https://jsonplaceholder.typicode.com"
def get_posts(self, amount):
response = self.client.request(method="GET", url=f"{self.base_url}/posts/{amount}")
if response.ok:
return response.json()
return response.status_code
And now the testing part
test_data.py
class TestPost(unittest.TestCase):
@patch('app.client.HttpClient')
def setUp(self, module):
self.mock_http = MagicMock(autospec=HttpClient)
self.mock_post = Post(self.mock_http)
@patch.object(requests, 'get')
def test_get_posts(self, mock_data):
mock_data.return_value = {
'postId': 1,
'title': 'My title',
'description': 'Post description'
}
response = self.mock_post.get_posts(1)
assert response['postId'] == 1
So does when I set mock_data.return_value it actually replace the original response that is being called here response = self.mock_post.get_posts(1) or not?
Maybe someone could explain how this exactly works
Thank You!