Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何模拟helper类的init_Python_Python 3.x_Unit Testing_Mocking_Pytest - Fatal编程技术网

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)