Mocked Class&断言方法调用

时间:2015-03-08 07:29:44

标签: python unit-testing mocking

难以理解如何模拟一个类,并能够断言它的'方法是用一些参数调用的。当我断言调用时,我得到一个“未调用”断言但是,我可以在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,我需要再次传递params。仅在call中使用mock_reference.call.method_a也不起作用。

访问mock_calls时输出call().method_a.mock_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.

1 个答案:

答案 0 :(得分:13)

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

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

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