python - 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()
不会引发任何错误,因为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
对你有用:
将规范添加到模拟。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.!
推荐阅读
- flutter - 不同的模型作为函数的输入
- c# - 我的 WPF 应用程序的当前上下文中不存在名称“InitializeComponent”
- mysql - 在 shell 脚本中运行 MYSQL 命令不起作用
- javascript - 需要有关添加到购物车按钮位置的数量按钮的帮助
- django - Django:文件对象不是 Json 可序列化的
- java - 在 macOS 中安装 java 后出现错误:无法确定当前工作目录
- git - Windows 凭据未显示 github
- css - 如何在 HTML 中更改组件的图标
- javascript - 在 mongoose 中插入很多,而不是用方案中的默认值保存文档
- reactjs - 错误:无效的挂钩调用。钩子只能在体内调用