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
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!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 methodLast updated