Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Mocking and Test Isolation | Testing with unittest and pytest
Python Structural Programming

Mocking and Test Isolation

Swipe to show menu

Mocking is a powerful technique in unit testing that allows you to replace parts of your system under test with mock objects or functions. The goal is to isolate the unit of code you are testing from its dependencies, such as databases, APIs, or other complex systems. By using mocks, you can control the behavior of dependencies and focus on testing the logic of your code in a controlled environment.

Test isolation is important because it ensures that tests do not interfere with each other and are not affected by factors outside their scope. Isolated tests are more reliable and easier to debug because their outcomes depend only on the code under test and the specific conditions you set up, not on the state or behavior of external systems.

In Python, the unittest.mock module provides tools for mocking objects and functions. When you use mocking, you can replace a real function or object with a mock that returns controlled values or records how it was used. This is especially useful when your code interacts with resources that are slow, unpredictable, or unavailable during testing.

1234567891011121314151617181920212223242526
import unittest from unittest.mock import patch def check_the_sky(): # Simulate a slow or unreliable API raise ConnectionError("API not available") def get_advice(): if check_the_sky(): return "Take an umbrella." else: return "Enjoy the sunshine!" class TestWeather(unittest.TestCase): @patch('__main__.check_the_sky') def test_advice_when_rainy(self, mock_check): mock_check.return_value = True self.assertEqual(get_advice(), "Take an umbrella.") @patch('__main__.check_the_sky') def test_advice_when_clear(self, mock_check): mock_check.return_value = False self.assertEqual(get_advice(), "Enjoy the sunshine!") unittest.main(argv=[''], exit=False)

In this code sample, the check_the_sky function simulates an external dependency that is unreliable or broken, such as a weather API that may not always be available. The get_advice function contains the logic you want to test — it calls check_the_sky and returns advice based on the result.

The unittest test class uses mocking to replace the real check_the_sky function with a mock that returns controlled values. This allows you to test how get_advice behaves in different scenarios, such as when the sky is clear or rainy, without relying on the actual external system.

The @patch decorator is used to temporarily replace the real check_the_sky function with a mock object during each test method. The mock object is passed to the test method as the mock_check parameter. You use mock_check to set the return value you want for that test, so you can control how your code behaves and what it returns in each scenario.

Note
Note

Function unittest.main() in this lesson includes a couple of extra parameters required only for this learning environment. They help the code run correctly on the platform and are not part of the core Python concepts you need to learn right now.

By using mocking, you isolate your tests from external systems that may be slow or unreliable. This makes your tests fast, repeatable, and deterministic, because you control exactly what the dependency returns in each test case.

question mark

When should you use mocking in unit tests?

Select all correct answers

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 5. Chapter 4

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

Section 5. Chapter 4
some-alt