Mock object but also assert method calls?

Ben Finney ben+python at benfinney.id.au
Thu Aug 13 23:21:54 CEST 2015


Thomas Lehmann via Python-list <python-list at python.org> writes:

> How about asserting that test2 of class Bar is called?

It is unusual to call class methods; do you mean a method on an
instance?

You will make a mock instance of the class, or a mock of the class; and
you'll need to know which it is.

> Of course I can do a patch for a concrete method but I was looking for
> something like:
>
>     mocked_object.assert_method_called_with(name="test2", "hello")

The ‘mock’ library defaults to providing ‘MagicMock’, which is “magic”
in the sense that it automatically provides any attribute you request,
and those attributes are themselves also MagicMocks::

    import unittest.mock

    def test_spam_calls_foo_bar():
        """ Should call the `spam` method on the specified `Foo` instance. """
        mock_foo = unittest.mock.MagicMock(system_under_test.Foo)
        system_under_test.spam(mock_foo)
        mock_foo.spam.assert_called_with("hello")

> If find following totally different to the normal API which
> is provided by the mock library:
>
> assert call().test2("hello") in mocked_objects.mock_calls

The ‘assert’ statement is a crude tool, which knows little about the
intent of your assertion. You should be instead using the specialised
methods from ‘unittest.TestCase’ and the methods on the mock objects
themselves.

-- 
 \       “It is the mark of an educated mind to be able to entertain a |
  `\                         thought without accepting it.” —Aristotle |
_o__)                                                                  |
Ben Finney



More information about the Python-list mailing list