How to use unittest mock side_effect with a sequence in Python

Demonstrates using Mock.side_effect with a list to return different values per call and raise an exception at a specific call in unittest.

Easy Python 3.9+ Aug 9, 2026 Testing & modern typing 13 views 0 copies

Python code

18 lines
Python 3.9+
import unittest
from unittest.mock import Mock

class TestMockSideEffectSequence(unittest.TestCase):
    def test_side_effect_sequence(self):
        mock = Mock()
        mock.side_effect = [1, 2, 3, Exception("boom")]
        
        self.assertEqual(mock(), 1)
        self.assertEqual(mock(), 2)
        self.assertEqual(mock(), 3)
        
        with self.assertRaises(Exception) as context:
            mock()
        self.assertEqual(str(context.exception), "boom")

if __name__ == "__main__":
    unittest.main()

Output

stdout
Ran 1 test in 0.001s

OK

How it works

The side_effect attribute when set to a list (or any iterable) makes the Mock return each item in sequence on successive calls. Once the list is exhausted, the Mock raises a StopIteration error unless the list contains an exception class or instance, which is raised instead. This is useful for simulating a function that varies its behavior across calls, like a flaky API client or a stateful parser.

Common mistakes

  • Using a tuple or set which might be sorted or unordered; use a list to preserve order
  • Forgetting that side_effect overrides return_value when both are set
  • Not accounting for extra calls after the sequence ends, which raise StopIteration unless the sequence includes an exception

Variations

  1. Use side_effect with a generator function to compute return values dynamically
  2. Set side_effect to a callable that returns different values based on call count

Real-world use cases

  • Mocking a database connection that returns different rows on consecutive queries.
  • Simulating an API endpoint that sometimes returns errors or retries.
  • Testing a retry loop by making a function fail on first calls and succeed later.

Sponsored

Run this sample

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

Open editor

More from Testing & modern typing

Related tutorials and quizzes for this topic.