79. Mocking in Tests with unittest.mock
Here are Python code examples for simulating objects and behaviors in unit tests using unittest.mock:
1. Mocking a Function Return Value
In this example, the mock object is used to simulate a function's return value.
import unittest
from unittest.mock import Mock
def fetch_data():
return "Real Data"
class TestMocking(unittest.TestCase):
def test_mock_function(self):
mock = Mock(return_value="Mocked Data")
result = mock()
self.assertEqual(result, "Mocked Data")
if __name__ == '__main__':
unittest.main()2. Mocking an Object Method
Here, we mock an object’s method to simulate specific behavior.
3. Mocking a Class Constructor
This snippet demonstrates mocking the constructor of a class to return a mock object.
4. Mocking a File Read Operation
Here we mock the behavior of reading a file to simulate file operations.
5. Mocking a Property
In this example, we mock a class property to simulate its behavior.
6. Mocking an External API Request
This demonstrates mocking an external API call to avoid hitting the real API in unit tests.
7. Mocking Side Effects
In this example, a side effect is used to simulate an exception being raised during method calls.
8. Mocking Multiple Return Values
This example demonstrates how to simulate different return values for consecutive calls to a mocked method.
9. Mocking a Method with Arguments
This snippet shows how to mock methods that take arguments and return a value based on those arguments.
10. Mocking an Iterable Object
In this example, the mock object is used to simulate an iterable object.
These examples demonstrate various ways to mock functions, methods, classes, and external APIs using unittest.mock. Mocking allows you to simulate complex behaviors, test edge cases, and isolate components, ensuring your tests are faster and more reliable.
Last updated