2017-05-15 31 views
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上

回答

0

assert_called_once使用Python 3.4.6在3.4不存在。它直到3.6才存在。如果你是3.4,你可以使用assert_called_once_with

+1

据*的* [记录](https://docs.python.org/3/library/unittest.mock .html#unittest.mock.Mock.assert_called_once)在3.6中是新的。在3.4中没有'assert_called_once'行为,你只是像调用其他方法一样调用模拟方法。 – jonrsharpe

+0

我修改了我的答案。一个不幸的蟒蛇嘲笑灵活性。 – kevswanberg

+0

在3.5中它是一个'AttributeError',因为任何启动'assert_'但没有实现的方法似乎都是。 – jonrsharpe

0

运行这样的测试:

python -m unittest tests 
相关问题