10. Mocking in Unit Tests

These snippets showcase a variety of ways to use unittest.mock for testing in Python, including mocking functions, classes, attributes, and dependencies, as well as asserting calls and handling side e

1. Mocking a Simple Function

Copy

from unittest.mock import Mock

# Original function
def greet():
    return "Hello!"

# Mock the function
mock_greet = Mock(return_value="Hi there!")
print(mock_greet())  # Output: Hi there!

2. Mocking Method Calls in a Class

Copy

from unittest.mock import MagicMock

class MyClass:
    def method(self):
        return "Real method"

obj = MyClass()
obj.method = MagicMock(return_value="Mocked method")
print(obj.method())  # Output: Mocked method

3. Asserting Function Calls

Copy


4. Mocking a Module Dependency

Copy


5. Mocking an Object Attribute

Copy


6. Mocking a Class

Copy


7. Mocking with Side Effects

Copy


8. Mocking a Context Manager

Copy


9. Mocking Multiple Calls with Different Results

Copy


10. Using Mock in Unit Test Class

Copy


Last updated