使用模拟python断言对方法的调用

2024-09-27 19:12:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用Python中的mock库进行一些单元测试。我有以下代码:

def a():
    print 'a'

def b():
    print 'b'
    if some condition
        a()

当对b进行模拟调用时,如何断言已对b进行了调用?我尝试了以下代码,但失败了:

mymock=Mock()
mymock.b()
assertTrue(a.__call__ in mymock.mock_calls)

出于某种原因,我认为mymock.b()与方法b()无关。对此能做些什么?


Tags: 代码inifdefsome断言单元测试call
2条回答

如果对a进行修补,则可以确保按如下方式调用它:

with mock.patch('__main__.a') as fake_a:
    b()
    fake_a.assert_called_with()

如果方法位于其他模块中:

import mymodule

with mock.patch('mymodule.a') as fake_a:
    mymodule.b()
    fake_a.assert_called_with()

Somehow, I think that the mymock.b() has nothing to do with the method b() What can be done for this?

你说得对。当你模仿一个对象时,你是在暗示你不在乎你的模仿在幕后做什么。如果要确保从b调用a,则需要在bpatcha

>>> from mock import patch
>>> with patch('__main__.a') as patch_a:
...     b()
...     patch_a.assert_called_with()

所以,这个故事的寓意是,模仿或修补你想测量的对象而不是你关心的对象实现。在本例中,您关心b,并希望了解它如何使用a。既然我们不在乎a做什么,只要它被调用,我们就可以修补它。

此外,如果您希望获得有关对a的调用的更多详细信息,而不是assert_called_with,则可以通过访问patchesmock_calls属性来分析所有调用。在这种情况下应该是patch_a.mock_calls

相关问题 更多 >

    热门问题