In this lesson, you will learn how to create simple stubs to replace unpredictable functions with reliable, hard-coded return values for your unit tests.
Why Use Stubs?
When writing unit tests, you often encounter functions that rely on external systems—like querying a volatile database, calling a live weather API, or reading from a system clock. These "non-deterministic" behaviors make tests brittle; they might pass one moment and fail the next simply because the external environment changed.
A stub is a simple object that replaces the real implementation of a dependency. Its only job is to return a predetermined value whenever it is called, ensuring that your test environment remains stable and predictable.
Implementing a Basic Stub
Imagine you have a function get_user_status() that performs a slow network request to a remote server. Instead of forcing your test to wait for the network, you can replace the network-calling function with a stub.
# The original function we want to isolate
def fetch_server_time():
# Imagine this hits a slow network API
pass
# Our test needs to know what happens if the server returns "200 OK"
def test_process_status():
# Create a stub: a simple function that returns a fixed value
def stub_fetch_server_time():
return "200 OK"
# Inject the stub into your logic instead of the real function
result = process_data(time_provider=stub_fetch_server_time)
assert result == "Success"
In this example, stub_fetch_server_time acts as our stub. It doesn't perform any logic or network calls; it strictly provides the input necessary for us to test the process_data function’s internal logic. By controlling the input, we can verify that our code handles the "200 OK" scenario exactly as expected, every single time the test runs.
Stubs aren't meant to mimic complex behavior or track how many times they were called; they exist solely to bridge the gap between your test code and the dependencies that would otherwise cause instability.
Key Takeaway: Stubs allow you to isolate the logic you are testing by providing simple, hard-coded responses, effectively stripping away the unpredictability of external dependencies.