【问题标题】:How to mock init of helper class如何模拟助手类的初始化
【发布时间】:2018-11-30 08:28:12
【问题描述】:

我无法检查是否正在使用来自另一个对象实例的正确参数构造对象。在下面的示例中,我试图在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

我不太确定我在这里做错了什么,并查看了其他堆栈溢出帖子,但未能解决我的问题。

b.py:

class B(object):
    def __init__(self, x):
        self.x = x

    def square(self):
        return x * x

a.py:

from b import B

class A(object):
    def foo(self):
        b = B(4)
        b.square()

test_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)

【问题讨论】:

    标签: python python-3.x unit-testing mocking pytest


    【解决方案1】:

    assert_called_with方法返回None,所以你在做的就像在做

    assert None
    

    这基本上就是您收到的错误消息。

    你可以使用

    mock_b.assert_called_with(4)
    

    其中有一个内部断言,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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-02
      • 1970-01-01
      • 1970-01-01
      • 2019-01-06
      • 2022-01-19
      • 1970-01-01
      相关资源
      最近更新 更多