繁体   English   中英

python mock:配置模拟对象的规范

[英]python mock: configure spec of a mock object

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

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()不会引发任何错误,因为two Mock 对象没有分配任何规范。

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

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

经过一些评论,看起来mock_add_spec对你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.! 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM