断言在 Python 单元测试中调用了一个方法 [英] Assert that a method was called in a Python unit test

查看:38
本文介绍了断言在 Python 单元测试中调用了一个方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在 Python 单元测试中有以下代码:

Suppose I have the following code in a Python unit test:

aw = aps.Request("nv1")
aw2 = aps.Request("nv2", aw)

是否有一种简单的方法可以断言在测试的第二行期间调用了特定方法(在我的情况下为 aw.Clear())?例如有没有这样的:

Is there an easy way to assert that a particular method (in my case aw.Clear()) was called during the second line of the test? e.g. is there something like this:

#pseudocode:
assertMethodIsCalled(aw.Clear, lambda: aps.Request("nv2", aw))

推荐答案

我使用 Mock(现在是 py3.3+ 上的 unittest.mock)为此:

I use Mock (which is now unittest.mock on py3.3+) for this:

from mock import patch
from PyQt4 import Qt


@patch.object(Qt.QMessageBox, 'aboutQt')
def testShowAboutQt(self, mock):
    self.win.actionAboutQt.trigger()
    self.assertTrue(mock.called)

对于您的情况,它可能如下所示:

For your case, it could look like this:

import mock
from mock import patch


def testClearWasCalled(self):
   aw = aps.Request("nv1")
   with patch.object(aw, 'Clear') as mock:
       aw2 = aps.Request("nv2", aw)

   mock.assert_called_with(42) # or mock.assert_called_once_with(42)

Mock 支持很多有用的功能,包括修补对象或模块的方法,以及检查是否调用了正确的东西等.

Mock supports quite a few useful features, including ways to patch an object or module, as well as checking that the right thing was called, etc etc.

注意清空者!(买家注意!)

Caveat emptor! (Buyer beware!)

如果你输入错误assert_call_with(到assert_Called_onceassert_call_wiht)你的测试可能仍然运行,因为Mock 会认为这是一个模拟函数并且愉快地继续吧,除非你使用 autospec=true.如需了解更多信息,请阅读assert_Called_once:威胁或威胁.

If you mistype assert_called_with (to assert_called_once or assert_called_wiht) your test may still run, as Mock will think this is a mocked function and happily go along, unless you use autospec=true. For more info read assert_called_once: Threat or Menace.

这篇关于断言在 Python 单元测试中调用了一个方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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