[TIP] Testing multiple calls of the same method

Jean-Yves LEBLEU jlebleu at gmail.com
Tue Jun 21 01:56:58 PDT 2011

Hi all,

First thanks for the mock library, coming from the java world were I
used to test everything I find it very usefull and very easy to use.

I came across the pb to test a method calling many times the same
method of another object and I did not find any very good solution to
this problem, except poping out the last call and checking the call in
reverse order as in

An other solution is to check if the call was made with arguments
without any assertion of the order of the call, so I have implemented
another assert_called_with  checking the call  was done once with the
correct arguments.

    def assert_was_called_with(self, *args, **kwargs):
        assert that the mock was called with the specified arguments.

        Raises an AssertionError if the args and keyword args passed in are
        different to the last call to the mock.
        if self.call_args is None:
            raise AssertionError('Expected: %s\nNot called' % ((args, kwargs),))
        for xargs in self.call_args_list:
            print xargs
            if xargs == (args, kwargs):

        raise AssertionError(
            'Expected: %s\nCalled with: %s' % ((args, kwargs), self.call_args)

Hope this will help.

More information about the testing-in-python mailing list