Search code examples
pythonpython-unittestpython-unittest.mock

How can I assert a mock object was not called with specific arguments?


unittest.mock objects have an assert_not_called method available, but what I'm looking for is an assert_not_called_with. Is there anything like that? I looked on Google and didn't see anything, and when I tried just using mock_function.assert_not_called_with(...) it raised an AttributeError, meaning the function does not exist with that name.

My current solution:

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

This works but clutters the code if I have several such calls I want to make.

Related:


Solution

  • One more solution that uses mock calls history:

    from unittest.mock import call
    
    assert call(arguments_I_want_to_test) not in mock_function.mock_calls