首页 > 解决方案 > python mock:配置模拟对象的规范

问题描述

我有一个实例方法,它启动另一个类的对象。例如,

import module_two
class One:
    def start(self):
        self.two = module_two.Two()

我在我的测试用例中修补一个类

@patch('module_one.One', autospec=True)
def test_one(patched_one):
    two = patched_one.return_value

    # Following method should raise error, but doesn't
    two.any_random_non_existing_method()

如前所述,two.any_random_non_existing_method()不会引发任何错误,因为twoMock 对象没有分配任何规范。

如何将规范分配给two对象。?我正在寻找类似以下片段的内容。

    # note: configure_spec actually doesn't exist.!
    two.configure_spec(module_two.Two)
    two.any_random_non_existing_method() # Error.! 

标签: pythonunit-testingmocking

解决方案


经过一些评论,看起来mock_add_spec对你有用:

将规范添加到模拟。spec 可以是一个对象或字符串列表。只有规范上的属性可以作为属性从模拟中获取。

https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock.mock_add_spec

这是它的外观:

# Add specifications on existing mock object
two.mock_add_spec(module_two.Two)
two.any_random_non_existing_method() # Error.! 

推荐阅读