我意识到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)
这可以工作,但是如果我要打几个这样的调用,则会使代码混乱。
答案 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)