python-3.x - 修补导入的类方法并断言如果调用一次
问题描述
我有一个名为 SomeClass 的类的 a.py 我有一个正在导入 SomeClass 并调用 SomeClass 的 my_method 的 b.py 文件
在 .py 文件中
class SomeClass:
def my_method(self, x):
return x * x
在 b.py 文件中
from a import SomeClass
class XYZ:
def new_fn(self):
x = SomeClass()
return x.my_method(2)
当我写这个时,在 b 的单元测试中
from unittest import TestCase
from unittest.mock import patch, MagicMock
from b import XYZ
class Test(TestCase):
@patch("b.SomeClass")
def test_b(self, patched):
patched.my_method = MagicMock()
b_i = XYZ()
b_i.new_fn()
patched.my_method.assert_called_once_with(2)
收到此错误 AssertionError: Expected 'my_method' to be called 一次。调用 0 次。
解决方案
推荐阅读
- vue.js - Vuex store 不能在 axios 处理程序中使用
- google-drive-api - 如何在不需要用户登录的情况下上传到 google drive api?
- nginx - Cloudflare 和 Nginx 代理管理器出现问题,无法连接到我的本地服务器。(错误 522/523)
- java - 运算符 ^ 未定义参数类型 long, boolean
- pandas - 我将如何访问这个 pandas dataFrame 的各个元素?
- php - 密码验证不断返回错误的登录凭据php
- python - 如何将数字按 5 分组?
- php - 将上传的图片从 Mysql 渲染到前端
- macos - 无法使用新的 Mac M1 构建 Docker 映像
- angular - Angular:通过http请求进行网络查询,但得到CORS错误