Python 简明教程
Python - Mocking and Stubbing
Python mocking and stubbing 是单元测试中的重要技术,它通过用受控的替代品替换真实对象或方法来帮助隔离被测功能。在本章中,我们将详细了解 Mocking 和 Stubbing:
Python mocking and stubbing are important techniques in unit testing that help to isolate the functionality being tested by replacing real objects or methods with controlled substitutes. In this chapter we are going to understand about Mocking and Stubbing in detail −
Python Mocking
Mocking 是一种测试技术,其中创建模拟对象来模拟真实对象的 behavior。
Mocking is a testing technique in which mock objects are created to simulate the behavior of real objects.
在测试与复杂、不可预测或缓慢组件(如数据库、Web 服务或硬件设备)交互的代码段时,这非常有用。
This is useful when testing a piece of code that interacts with complex, unpredictable or slow components such as databases, web services or hardware devices.
模拟的主要目的是隔离被测代码,并确保对其 behavior 的评估独立于其依赖项。
The primary purpose of mocking is to isolate the code under test and ensure that its behavior is evaluated independently of its dependencies.
Key Characteristics of Mocking
以下是 Python 中模拟的关键特征:
The following are the key characteristics of mocking in python −
-
Behavior Simulation: Mock objects can be programmed to return specific values, raise exceptions or mimic the behavior of real objects under various conditions.
-
Interaction Verification: Mocks can record how they were used by allowing the tester to verify that specific methods were called with the expected arguments.
-
*Test Isolation:*By replacing real objects with mocks, tests can focus on the logic of the code under test without worrying about the complexities or availability of external dependencies.
Example of Python Mocking
以下是对 database.get_user 方法的示例,该方法被模拟为返回预定义的用户词典。然后,测试可以验证是否使用正确的参数调用了该方法:
Following is the example of the database.get_user method, which is mocked to return a predefined user dictionary. The test can then verify that the method was called with the correct arguments −
from unittest.mock import Mock
# Create a mock object
database = Mock()
# Simulate a method call
database.get_user.return_value = {"name": "Prasad", "age": 30}
# Use the mock object
user = database.get_user("prasad_id")
print(user)
# Verify the interaction
database.get_user.assert_called_with("prasad_id")
Output
{'name': 'Prasad', 'age': 30}
Python Stubbing
Stubbing is a related testing technique where certain methods or functions are replaced with "stubs" that return fixed, predetermined responses.
存根比模拟简单,因为它通常不涉及记录或验证交互。相反,存根专注于通过确保一致且可重复的结果来向测试中的代码提供受控输入。
Stubbing is simpler than mocking because it typically does not involve recording or verifying interactions. Instead, stubbing focuses on providing controlled inputs to the code under test by ensuring consistent and repeatable results.
Key Characteristics of Stubbing
以下是在 python 中存根的关键特征 −
The following are the key characteristics of Stubbing in python −
-
Fixed Responses: Stubs return specific, predefined values or responses regardless of how they are called.
-
Simplified Dependencies: By replacing complex methods with stubs, tests can avoid the need to set up or manage intricate dependencies.
-
Focus on Inputs: Stubbing emphasizes providing known inputs to the code under test by allowing the tester to focus on the logic and output of the tested code.
Example of Python Stubbing
以下是 get_user_from_db 函数的示例,该函数被存根来始终返回预定义的用户词典。测试不必与真正的数据库交互,以简化设置和确保结果一致 −
Following is the example of the get_user_from_db function, which is stubbed to always return a predefined user dictionary. The test does not need to interact with a real database for simplifying the setup and ensuring consistent results −
from unittest.mock import patch
# Define the function to be stubbed
def get_user_from_db(user_id):
# Simulate a complex database operation
pass
# Test the function with a stub
with patch('__main__.get_user_from_db', return_value={"name": "Prasad", "age": 25}):
user = get_user_from_db("prasad_id")
print(user)
Output
{'name': 'Prasad', 'age': 25}
Python Mocking Vs. Stubbing
模拟和存根的关键特性、目的和用例的比较明确说明了在何时使用每种方法。通过探索这些区别,开发者可以创建更有效和可维护的测试,最终构建更高质量的软件。
The comparison of the Mocking and Stubbing key features, purposes and use cases gives the clarity on when to use each method. By exploring these distinctions, developers can create more effective and maintainable tests which ultimately leads to higher quality software.
下表根据不同的条件展示了模拟和存根之间的主要区别 −
The following table shows the key difference between mocking and stubbing based on the different criteria −