Python-如何断言未使用特定参数调用模拟对象?

时间:2019-02-23 04:52:12

标签: python python-unittest python-unittest.mock

我意识到unittest.mock对象现在有一个assert_not_called方法可用,但是我正在寻找的是assert_not_called_with。有没有类似的东西?我在Google上查看时没有看到任何内容,当我尝试仅使用mock_function.assert_not_called_with(...)时,它引发了AttributeError,这意味着该功能不存在该名称。

我当前的解决方案

with self.assertRaises(AssertionError):
    mock_function.assert_called_with(arguments_I_want_to_test)

这可以工作,但是如果我要打几个这样的调用,则会使代码混乱。

相关

Assert a function/method was not called using Mock

2 个答案:

答案 0 :(得分:3)

您可以自行向assert_not_called_with添加unittest.mock.Mock方法:

from unittest.mock import Mock

def assert_not_called_with(self, *args, **kwargs):
    try:
        self.assert_called_with(*args, **kwargs)
    except AssertionError:
        return
    raise AssertionError('Expected %s to not have been called.' % self._format_mock_call_signature(args, kwargs))

Mock.assert_not_called_with = assert_not_called_with

这样:

m = Mock()
m.assert_not_called_with(1, 2, a=3)
m(3, 4, b=5)
m.assert_not_called_with(3, 4, b=5)

输出:

AssertionError: Expected mock(3, 4, b=5) to not have been called.

答案 1 :(得分:0)

使用 Pytest,我断言调用了“AssertionError”:

import pytest
from unittest.mock import Mock


def test_something():
    something.foo = Mock()
    
    # Test that something.foo(bar) is not called.
    with pytest.raises(AssertionError):
        something.foo.assert_called_with(bar)
相关问题