How to Create a Sticky Consistent Mock with unittest.mock in Python

Shows how to use unittest.mock.patch.object to mock a method consistently across multiple calls, returning a sticky value every time.

Easy Python 3.8+ Aug 9, 2026 A/B testing & experimentation 15 views 0 copies

Python code

18 lines
Python 3.8+
from unittest.mock import patch

class Database:
    def fetch(self, key):
        return f"real value for {key}"

def get_value(db, key):
    return db.fetch(key)

if __name__ == "__main__":
    db = Database()
    with patch.object(db, "fetch", return_value="sticky value") as mock_fetch:
        result1 = get_value(db, "user:1")
        result2 = get_value(db, "user:2")

    print("First call:", result1)
    print("Second call:", result2)
    print("Mock called:", mock_fetch.call_count)

Output

stdout
First call: sticky value
Second call: sticky value
Mock called: 2

How it works

The patch.object context manager temporarily replaces the fetch method on the db instance with a Mock that returns the fixed string "sticky value" whenever called. Because the mock persists for the entire with block, both calls to get_value return the same consistent result, demonstrating a sticky mock. After the block exits, the original method is restored automatically, so the mock does not leak into other tests. The call_count attribute confirms the mock was invoked twice, proving the sticky behavior across multiple calls.

Common mistakes

  • Forgetting that the mock is restored on exit, so calling it outside the `with` block hits the real method.
  • Using `patch` without `object` when you need to target an instance method, causing the mock to affect all instances.
  • Assuming `call_count` resets between tests without explicitly clearing the mock.

Variations

  1. Use `patch('module.Database.fetch', return_value='sticky value')` to mock the method at class level rather than instance level.
  2. Use `mock_fetch.side_effect = lambda key: "sticky value"` to customize behavior per call.

Real-world use cases

  • Simulating a consistent A/B test assignment so the same user always sees the same variant during a session.
  • Stubbing a database call in unit tests to return a fixed value, isolating logic from real data.
  • Mocking an external API dependency to verify your code handles repeated identical responses gracefully.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from A/B testing & experimentation

Related tutorials and quizzes for this topic.