Member-only story

Mocking APIs in Python Tests with pytest and SOLID Principles

Neural pAi
3 min readMar 25, 2023

Introduction:

When building applications that rely on external APIs, it’s important to test your code thoroughly. One way to do this is by mocking the API responses during testing. In this article, we will explore how to mock APIs in Python using the pytest library while adhering to the SOLID principles. We will create a simple user management system, complete with a User class, UserService class for managing users, and UserRepository class for interacting with the API.

Creating the User, UserRepository, and UserService Classes

First, let’s define our classes. We will create a User class to represent a user, a UserRepository class for interacting with the API, and a UserService class for managing user data.

user.py:

class User:
def __init__(self, id: int, name: str, email: str):
self.id = id
self.name = name
self.email = email

@classmethod
def from_json(cls, json_data: dict):
return cls(id=json_data["id"], name=json_data["name"], email=json_data["email"])

user_repository.py:

import requests
from user import User

class UserRepository:
def __init__(self, base_url: str):
self.base_url =…

--

--

No responses yet