【问题标题】:Mocked Class & Asserting Method Calls模拟类和断言方法调用
【发布时间】:2015-03-08 07:29:44
【问题描述】:

不知道如何模拟一个类并能够断言它的方法是用一些参数调用的。当我断言调用时,我得到一个“未调用”断言,但是,我可以在 mock_calls 属性中看到方法调用。

sandbox/module.py

class Subject(object):
    def __init__(self):
        pass

    def run(self, *args, **kwargs):
        reference = Reference(*args, **kwargs)
        reference.method_a(*args)


class Reference(object):
    def __init__(self, *args, **kwargs):
        pass

    def method_a(self, *args):
        pass

test.py

import unittest
from unittest import mock
from sandbox.module import Subject


class TestSandbox(unittest.TestCase):

    @mock.patch('sandbox.module.Reference')
    def test_method_calls(self, mock_reference):
        subject = Subject()
        subject.run(1, 2, 3, x=44, y=55, z=66)
        mock_reference.assert_called_with(1, 2, 3, x=44, y=55, z=66)
        mock_reference.method_a.assert_called_with(1, 2, 3)

结果是

AssertionError: Expected call: method_a(1, 2, 3)  
Not called

mock_reference.mock_calls的值为

[
    call(1, 2, 3, x=44, y=55, z=66), 
    call().method_a(1, 2, 3)
]

如果我以call().method_a 访问调用,我可以访问方法详细信息,但是mock_calls 会添加一个call() 项目。这可能会以我没想到的方式改变assert_called_once_with,而且感觉不太对劲。此外,如果使用autospec=True,我需要再次传递参数。像mock_reference.call.method_a 那样只使用call 也不起作用。

访问call().method_a.mock_callsmock_calls的输出

mock_reference().method_a.mock_calls

[
    call(1, 2, 3, x=44, y=55, z=66), 
    call().method_a(1, 2, 3),
    call()
]    

mock_reference.assert_called_once_with(1, 2, 3)

AssertionError: Expected 'Reference' to be called once. Called 2 times.

【问题讨论】:

    标签: python unit-testing mocking


    【解决方案1】:

    您模拟了一个类,但在实例上调用了第二个方法。改变

    mock_reference.method_a.assert_called_with(1, 2, 3)
    

    mock_reference.return_value.method_a.assert_called_with(1, 2, 3)
    

    【讨论】:

    • 太棒了。这以一种清晰易懂的方式工作。谢谢
    • 完美运行!希望我在 6 小时前看到这篇文章,而不是把它们浪费在尝试其他东西上
    猜你喜欢
    • 2016-03-08
    • 1970-01-01
    • 1970-01-01
    • 2011-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-25
    相关资源
    最近更新 更多