如何用Mock验证Python函数调用参数并执行条件校验?
用Mock验证method3的参数条件
没问题,这事儿用Python Mock库的call_args属性就能轻松实现,我给你结合你现有的测试代码来写具体实现:
首先,先确保你已经在setUp里完成了method2和method3的打桩(看你代码里只写了method1的,我补全一下):
import unittest from mock import patch, Mock class TestYourClass(unittest.TestCase): def setUp(self): # 打桩method1 patcher1 = patch("x.x.x.method1") self.object_method1_mock = patcher1.start() self.addCleanup(patcher1.stop) # 打桩method2 patcher2 = patch("x.x.x.method2") self.object_method2_mock = patcher2.start() self.addCleanup(patcher2.stop) # 打桩method3 patcher3 = patch("x.x.x.method3") self.object_method3_mock = patcher3.start() self.addCleanup(patcher3.stop) # 给method1和method2设置返回值,确保函数能顺利执行到调用method3的步骤 self.object_method1_mock.return_value = "mock_thing" self.object_method2_mock.return_value = "mock_thing_obj"
接下来就是核心的测试方法实现,步骤很清晰:调用待测试函数,提取method3的调用参数,然后校验条件:
def test_function(self): # 实例化你的待测试类 test_obj = YourActualClass() # 触发待测试的function test_obj.function() # 获取method3最后一次被调用的参数:call_args返回(位置参数元组, 关键字参数字典) method3_call_args = self.object_method3_mock.call_args[0] # 提取你要校验的参数:原调用是method3(thing_obj, 1, 2, 3, 4) # 位置参数索引0是thing_obj,1是第一个数值参数,2是你说的"第三个参数",3是你说的"第四个参数" third_param = method3_call_args[2] fourth_param = method3_call_args[3] # 用unittest的断言方法校验条件,报错信息更友好 self.assertLess(third_param, fourth_param, "第三个参数不满足小于第四个参数的要求")
补充说明:
- 如果
method3可能被调用多次,你可以用call_args_list来获取所有调用的参数,比如取第一次调用的参数就是self.object_method3_mock.call_args_list[0][0] assertLess是unittest自带的断言方法,专门用来判断前者小于后者,比自己写self.assertTrue(third_param < fourth_param)的报错信息更直观- 给method1和method2设置
return_value是为了让待测试的function能顺利走完逻辑,不然可能会因为返回值为None导致后续步骤中断
内容的提问来源于stack exchange,提问作者eniem
相关产品推荐
相关产品推荐

