首页 > 解决方案 > 修补导入的类方法并断言如果调用一次

问题描述

我有一个名为 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 次。

标签: python-3.xpython-unittestpython-unittest.mock

解决方案


推荐阅读