Python mock side effect raise exception

In Python, you can use the unittest.mock module to create mock objects and simulate side effects or raise exceptions. This module provides the side_effect attribute that allows you to define custom behavior for a function or method.

Here’s an example to demonstrate how to use the side_effect attribute to raise an exception:


import unittest.mock as mock

# Define a function with side effect
def my_function():
    raise ValueError("Custom exception")

# Create a mock object
mock_obj = mock.Mock()

# Configure the side effect to raise an exception
mock_obj.side_effect = my_function

# Call the mock object
mock_obj()  # This will raise a ValueError with "Custom exception"
  

The side_effect attribute of the mock object is set to the my_function function, which raises a ValueError with a custom exception message. When you call the mock object mock_obj(), it will execute the side effect function and raise the exception.

You can also specify a sequence of side effects or a callable object that returns the desired side effect. Here’s an example with a sequence of side effects:


# Define side effect functions
def side_effect_func1():
    return "Side effect 1"

def side_effect_func2():
    raise TypeError("Side effect 2")

# Create a mock object
mock_obj = mock.Mock()

# Configure sequence of side effects
mock_obj.side_effect = [side_effect_func1, side_effect_func2, None]

# Call the mock object multiple times
print(mock_obj())  # Output: "Side effect 1"
print(mock_obj())  # Raises a TypeError with "Side effect 2"
print(mock_obj())  # Output: None
  

In this example, the side_effect attribute is set to a list of side effect functions. The first time you call the mock object, it executes side_effect_func1 and returns the result. The second time, it executes side_effect_func2 and raises a TypeError. The third time, it returns None.

So, with the side_effect attribute of the mock object, you can define custom behavior including raising exceptions. This is helpful for testing scenarios where you need to trigger specific error conditions within your code.

Leave a comment