Python 如何模拟helper类的init
我在检查一个对象是否使用来自另一个对象实例的正确参数构造时遇到问题。在下面的示例中,我试图在Python 如何模拟helper类的init,python,python-3.x,unit-testing,mocking,pytest,Python,Python 3.x,Unit Testing,Mocking,Pytest,我在检查一个对象是否使用来自另一个对象实例的正确参数构造时遇到问题。在下面的示例中,我试图在A的实例中创建B的实例。我想检查A实例中B的构造函数中使用的参数。当我运行下面的测试时,我得到: AssertionError: assert None [CPython36:setup:stdout] E + where None = <bound method NonCallableMock.assert_called_with of <MagicMock name='B'
A
的实例中创建B
的实例。我想检查A
实例中B
的构造函数中使用的参数。当我运行下面的测试时,我得到:
AssertionError: assert None
[CPython36:setup:stdout] E + where None = <bound method NonCallableMock.assert_called_with of <MagicMock name='B' id='139968329210736'>>(4)
[CPython36:setup:stdout] E + where <bound method NonCallableMock.assert_called_with of <MagicMock name='B' id='139968329210736'>> = <MagicMock name='B' id='139968329210736'>.assert_called_with
a、 py:
测试a.py:
import unittest
from unittest.mock import patch
from a import A
class TestA(unittest.TestCase):
@patch('a.B')
def test_foo(self, mock_b):
self.a = A()
self.a.foo()
assert mock_b.assert_called_with(4)
方法
assert\u调用了\u with
返回None,因此您所做的就是这样做
assert None
这基本上就是你得到的错误信息
你可以用
mock_b.assert_called_with(4)
它内部有一个assert,pytest将在失败时正确显示它。尝试通过更改参数值来检查它
或者,如果您希望自己编写断言,可以执行以下操作:
from unittest.mock import call
assert mock_b.call_args_list == [call(4)]
或者只是最后一个电话:
from unittest.mock import call
assert mock_b.call_args == call(4)
from unittest.mock import call
assert mock_b.call_args_list == [call(4)]
from unittest.mock import call
assert mock_b.call_args == call(4)