20

我意识到unittest.mock对象现在有一个assert_not_called可用的方法,但我正在寻找的是一个assert_not_called_with. 有这样的吗?我在谷歌上查看并没有看到任何东西,当我尝试使用mock_function.assert_not_called_with(...)它时引发了一个AttributeError,这意味着该函数不存在该名称。

我目前的解决方案

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

这很有效,但如果我有几个这样的调用,我想打乱代码。

有关的

断言未使用 Mock 调用函数/方法

4

3 回答 3

26

您可以自己添加一个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.
于 2019-02-23T06:07:05.420 回答
2

使用 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)
于 2021-08-02T00:21:00.310 回答
2

另一种使用模拟呼叫历史的解决方案:

from unittest.mock import call

assert call(arguments_I_want_to_test) not in mock_function.mock_calls
于 2022-02-25T14:01:20.600 回答