【问题标题】:Python - How can I assert a mock object was not called with specific arguments?Python - 如何断言没有使用特定参数调用模拟对象?
【发布时间】:2019-07-17 05:06:53
【问题描述】:

我意识到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

【问题讨论】:

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


    【解决方案1】:

    您可以自行将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.
    

    【讨论】:

    • “ClassA”实例没有“assert_call_with”成员 - 如何解决这个问题?
    【解决方案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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多