Improve Your Tests With the Python Mock Object Library

Lee Gaines
Lee Gaines 31 Lessons 1h 29m intermediate testing

When you’re writing robust code, tests are essential for verifying that your application logic is correct, reliable, and efficient. However, the value of your tests depends on how well they demonstrate these criteria. Obstacles such as complex logic and unpredictable dependencies make writing valuable tests difficult. The Python mock object library, unittest.mock, can help you overcome these obstacles.

By the end of this course, you’ll be able to:

  • Create Python mock objects using Mock
  • Assert that you’re using objects as you intended
  • Inspect usage data stored on your Python mocks
  • Configure certain aspects of your Python mock objects
  • Substitute your mocks for real objects using patch()
  • Avoid common problems inherent in Python mocking

You’ll begin by seeing what mocking is and how it will improve your tests!

What’s Included:

Downloadable Resources:

Related Learning Paths:

About Lee Gaines

Lee is a DevOps Engineer and Pythonista based in Berkeley, California.

» More about Lee

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

Participant Comments

Avatar image for matiasm77

matiasm77 on Aug. 24, 2021

Now I know how to make my datetime testing not fail depending on hour, and of course all about mocking. Thanks!

Avatar image for Ghani

Ghani on Oct. 27, 2020

Very informative course; thanks!

Avatar image for alexign

alexign on Aug. 28, 2020

After that course I can’t wait to start mocking %)! Lee, thank you very much!

Avatar image for markjohnwilson

markjohnwilson on June 24, 2020

Really happy with this, a nice explanation of Mock, Patch and Spec.

Avatar image for David Alvarez

David Alvarez on June 19, 2020

I quite happy with this course. My previous attempt to try to understand mock module were unsuccessful, a lot of magic happening I didn’t understand. But Lee manage to make it accessible an at list get a glimpse of what is going on. Working usually with python as scripting language with heavy dependencies with software who run it, mock can be really useful to make test independent of this dependencies. I’m also like the way how Lee record this course. Have the opportunity of see him solve usual mistakes and difficulties everyone encounters in his day to day I think it help me in my learning journey.

« Browse All Courses