模拟课断言方法调用 [英] Mocked Class & Asserting Method Calls

查看:89
本文介绍了模拟课断言方法调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于如何模拟一个类并能够断言其方法是通过一些参数调用而感到困惑的.当我断言该调用时,我得到一个未调用"断言,但是,我可以在mock_calls属性中看到该方法调用.

Stumped on how to mock a class and be able to assert that its' methods are called with some arguments. When I assert the call i get a "Not called" assertion but, I can see the method call in the mock_calls attribute.

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也不起作用.

If I access call as call().method_a I can access the method details but, the mock_calls gets a item call() added to it. Which could change assert_called_once_with in a way i wouldn't expect and, doesn't feel quite right. Furthermore, if autospec=True is used I need to pass the params again. Using just call as in mock_reference.call.method_a does not work either.

访问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.

推荐答案

您嘲笑了一个类,但是在实例上调用了第二个方法.更改

You mocked a class, yet the second method is called on instance. Change

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

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

这篇关于模拟课断言方法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆