Let’s be Friends with Mock in Python

From Understanding It to Utizling for Your Tests

Yasufumi TANIGUCHI
9 min readSep 18, 2019
Photo by Susan Yin on Unsplash

When you start writing unit tests for your project, you might need to understand unittest.mock in Python. Imagine that you are making a library interacting with Google Spreadsheet and trying to test it. Do we need to connect Google Spreadsheet for every test? That sounds really time-consuming. What if your project gets bigger and bigger? Your HTTP connections are gonna be huge! But don’t worry, you don’t need to speed up your Wi-Fi or make a phone call to Google to say your requests aren’t DoS attack :)

In this post, I’ll explain unittest.mock, a built-in library for testing in Python, with some examples, which shows usages for your testing. Prepare your Python interpreter and follow with me. I bet this post is worth your time. Let’s get started! ​ ​

1. What is mocking?

A mock object substitutes and imitates a real object within a testing environment. It is a versatile and powerful tool for improving the quality of your tests. For example, if we test the module interacting with a server, it will cause HTTP connections for each test. But you don’t need to make a request with Mock. It’ll save time.

What we expect is that you can understand the code below after reading this section:

--

--

Yasufumi TANIGUCHI

Software engineer, My interest in Natural Language Processing