mock_method.side_effect =
Testing Patterns

Meaning

Sets the side_effect attribute of a mock method to return a sequence of values on successive calls.

Primary Function

Configures a mock method to return a predefined sequence of values on successive invocations.

Communicative Purpose

Instructs a test double to simulate a method that returns different values each time it is called, enabling deterministic testing of algorithms that depend on sequential outputs.

Pattern

<mock_object>.side_effect = [<value1>, <value2>, ...]

Core Structure

Assignment of a list of return values to the side_effect attribute of a mock object.

Função primária

Configures a mock method to return a predefined sequence of values on successive invocations.

Propósito comunicativo

Instructs a test double to simulate a method that returns different values each time it is called, enabling deterministic testing of algorithms that depend on sequential outputs.

Situações de gatilho

When writing unit tests that need to simulate a method returning different values on successive calls, such as paginated API responses, retry attempts, or iterative algorithms.

Contextos

Unit testing with Python's unittest.mock library, specifically when configuring Mock or MagicMock objects to emulate stateful dependencies.

Padrão

<mock_object>.side_effect = [<value1>, <value2>, ...]

Estrutura central

Assignment of a list of return values to the side_effect attribute of a mock object.

Slots de substituição

mock_method: any mock object or mock method (e.g., Mock, MagicMock); values: list of return values (any objects) to be returned on successive calls.

Colocados típicos

  • unittest.mock.Mock
  • unittest.mock.MagicMock
  • unittest.mock.patch
  • return_value
  • call_args_list
  • side_effect as iterable or callable

Substituições comuns

  • Using side_effect as an iterable (e.g.
  • iterator) instead of a list
  • using a lambda or callable to compute return values dynamically
  • using side_effect to raise exceptions
  • using return_value for a constant return value.

Erros comuns

- Using side_effect = None causing subsequent calls to return None, leading to unexpected None values in code under test;\n- Forgetting to reset side_effect between tests, causing state leakage and intermittent test failures;\n- Providing a side_effect list shorter than the number of calls, resulting in StopIteration exception when the mock is called more times than items;\n- Confusing side_effect with return_value, causing the mock to return the list itself instead of its elements;\n- Passing a non‑iterable non‑callable to side_effect, raising TypeError: 'object is not iterable' when the mock is invoked.

Similar / contraste

- return_value: sets a single return value for all calls, unlike side_effect which can vary per call;\n- side_effect as a callable: computes return value dynamically based on arguments, whereas a list side_effect returns pre‑defined values;\n- PropertyMock: used to mock properties rather than methods, requiring side_effect on the property descriptor.

Interferências

Coming from Java's Mockito: may expect thenReturn to provide a sequence of values; in Python's unittest.mock, side_effect must be an iterable or callable to achieve sequenced returns.\nComing from JavaScript's Jest: may assume mockImplementationOnce behaves like a list side_effect; in Python, side_effect consumes the iterable on each call, so the same list cannot be reused without resetting.

Família do chunk

  • mock configuration
  • mock return_value
  • mock side_effect
  • mock call_args_list
  • patch decorator

Nuance

(1) Avoid using side_effect for simple constant returns; use return_value instead for clarity and lower overhead. (2) side_effect as a list creates an iterator that is exhausted after the listed number of calls; subsequent calls raise StopIteration, which can cause unexpected test failures if not anticipated. (3) If side_effect is a callable, it receives the same arguments as the mock call; ensure the callable accepts *args, **kwargs or uses a signature‑matching wrapper to avoid TypeError.

Efeito pragmático

Ensures that a mocked method returns a predetermined sequence of values, making tests of algorithms that depend on sequential outputs (e.g., pagination, retry loops) deterministic and repeatable.

Dica de memória

Think of a mock method's side_effect as a PEZ dispenser loaded with a stack of candies; each press (call) dispenses the next candy in line.

Tipo de construção: attribute assignmentTag de espaçamento: Short-term

Log in to save chunks.