Member-only story

Python Mocking — Tutorial

Kamal Hussain
5 min readMay 19, 2021

--

Writing unit tests for programs that have external dependencies is tricky. One approach is mocking external dependencies. For example, if your program is writing to a MySQL database, you may not want to actually write to the database when you run unit tests. Instead, you can use a mock to simulate this operation.

Python’s unittest.mock allows you to replace parts of your program with mock objects and test various conditions. In other words, you can replace functions, classes, or objects in your program with mock objects, which are instances of Mock class.

Here is an example to understand the concept.

Function Mocks

Let’s start with a function that makes an API call to determine the weather basted latitude and longitude.

import requests
def get_weather_status(lat, lng):
response = requests.get(f"https://api.weather.gov/points/{lat},{lng}")
if response.status_code == 200:
return response.json()
else:
return None

The above function is called by check_weather and prints a status message.

def check_weather():
if get_weather(39.7456,-97.0892):
return "Got weather information"
else:
return "Can't get weather information"

--

--

No responses yet