在单元测试中使用补丁时模拟对象的顺序

order of mock objects while using patch in unittests

@patch('module1.api.method1')  
@patch('module1.api.method2')
class TestApi(unittest.TestCase):

        @patch('module1.api.connec1')    
        @patch('module1.api.connec2')  
        def test_some_method(self, mockMethod1, mockMethod2, 
                                mockConnec1, mockConnec2):
            # some code.....

测试方法中提到的模拟对象的顺序是否应该与patch相同?我们是否需要为所有 class 级别和方法级别补丁提及模拟对象?

如果有 20 个补丁对象,方法是否相同?

来自补丁文档:

When you nest patch decorators the mocks are passed in to the decorated function in the same order they applied (the normal Python order that decorators are applied). This means from the bottom up

所以您代码中的正确顺序是:

@patch('module1.api.method1')  
@patch('module1.api.method2')
class TestApi(unittest.TestCase):

        @patch('module1.api.connec1')    
        @patch('module1.api.connec2')  
        def test_some_method(self, mockConnec2, mockConnec1, mockMethod2, mockMethod1):
         # some code.....

如果你有很多这样的模拟并且你不需要在每个模拟中做任何事情(比如定义 side_effect 等),你可以用 *args 把它们卷起来为简洁起见。