0
在python单元测试它说mock.assert_called_once()将失败,如果它被调用多次。修补时,我没有看到这种行为。修补时,assert_called_once不失败,当它应该
ugh.py
def foo(*args):
pass
def bar():
foo(1)
foo(2)
tests.py
from unittest import TestCase, main
from unittest.mock import patch
from ugh import bar
class Test(TestCase):
@patch('ugh.foo')
def test_called_once(self, foo_mock):
bar()
foo_mock.assert_called_once()
@patch('ugh.foo')
def test_called_count_one(self, foo_mock):
bar()
self.assertEqual(foo_mock.call_count, 1)
if __name__ == '__main__':
main()
和测试输出。
razorclaw% python tests.py
F.
======================================================================
FAIL: test_called_count_one (__main__.Test)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/usr/lib64/python3.4/unittest/mock.py", line 1142, in patched
return func(*args, **keywargs)
File "tests.py", line 15, in test_called_count_one
self.assertEqual(foo_mock.call_count, 1)
AssertionError: 2 != 1
----------------------------------------------------------------------
Ran 2 tests in 0.002s
FAILED (failures=1)
在Linux上
据*的* [记录](https://docs.python.org/3/library/unittest.mock .html#unittest.mock.Mock.assert_called_once)在3.6中是新的。在3.4中没有'assert_called_once'行为,你只是像调用其他方法一样调用模拟方法。 – jonrsharpe
我修改了我的答案。一个不幸的蟒蛇嘲笑灵活性。 – kevswanberg
在3.5中它是一个'AttributeError',因为任何启动'assert_'但没有实现的方法似乎都是。 – jonrsharpe