如何在python 3.6下获得Mock()。assert_called_once之类的行为?

时间:2018-01-20 15:53:27

标签: python unit-testing mocking

如何使用unittest.mock.Mock().assert_called_once获得unittest.mock.Mock().assert_called_once_with行为,因为assert_called_once在python 3.6下面不可用。

基本上我想要的是检查方法是否被调用一次,无论是哪个参数或多少参数。

我试过了unittest.mock.ANY,但似乎并不是我想要的。

1 个答案:

答案 0 :(得分:2)

assert_called_once()所做的就是断言Mock.call_count attribute为1;你可以轻而易举地做同样的测试:

self.assertEqual(
    mock_object.call_count, 1,
    "Expected mock to have been called once. Called {} times.".format(
        mock_object.call_count))

如果您尝试将Mock.assert_called_once_with()ANY对象一起使用,请考虑该对象代表其中一个参数的值。 Mock.assert_called_once_with(ANY)仅在使用一个参数调用对象时才匹配,并且该参数的值无关紧要:

>>> from unittest.mock import Mock, ANY
>>> m = Mock()
>>> m(42, 81, spam='eggs')  # 2 positional arguments, one keyword argument
<Mock name='mock()' id='4348527952'>
>>> m.assert_called_once_with(ANY)   # doesn't match, just one positional argument
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/mjpieters/Development/Library/buildout.python/parts/opt/lib/python3.6/unittest/mock.py", line 825, in assert_called_once_with
    return self.assert_called_with(*args, **kwargs)
  File "/Users/mjpieters/Development/Library/buildout.python/parts/opt/lib/python3.6/unittest/mock.py", line 814, in assert_called_with
    raise AssertionError(_error_message()) from cause
AssertionError: Expected call: mock(<ANY>)
Actual call: mock(42, 81, spam='eggs')

您不能将ANY对象与*called_with断言一起用来表示“任意数量的参数”。只有在call() objects {{}}}的断言中才会将ANY解释为任意数量的参数;所以你也可以在这里使用Mock.assert_has_calls(),传入一个包含ANY元素的列表:

>>> m.assert_has_calls([ANY])  # no exception raised