【发布时间】:2016-03-08 03:09:47
【问题描述】:
我正在尝试为Bar 编写单元测试,以调用Foo 的方法read()。我在setUp() 中添加了patch 命令,因为其他测试也会使用这个patch。
问题
如何检查 read() 函数是否使用我期望的参数调用?
代码
foo.py
class Foo(object):
def __init__(self):
self.table = {'foo': 1}
def read(self, name):
return self.table[name]
bar.py
import foo
class Bar(object):
def act(self):
a = foo.Foo()
return a.read('foo')
test_bar.py
import bar
import unittest
from mock import patch
class TestBar(unittest.TestCase):
def setUp(self):
self.foo_mock = patch('bar.foo.Foo', autospec=True).start()
self.addCleanup(patch.stopall)
def test_can_call_foo_with_correct_arguments(self):
a = bar.Bar()
a.act()
self.foo_mock.read.assert_called_once_with('foo')
输出
python -m unittest discover
F
======================================================================
FAIL: test_can_call_foo_with_correct_arguments (test_bar.TestBar)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/test_dir/test_bar.py", line 12, in test_can_call_foo_with_correct_arguments
self.foo_mock.read.assert_called_once_with('foo')
File "/usr/local/lib/python2.7/dist-packages/mock.py", line 845, in assert_called_once_with
raise AssertionError(msg)
AssertionError: Expected to be called once. Called 0 times.
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (failures=1)
【问题讨论】:
-
你试过了吗?
self.foo_mock.return_value.read.assert_called_once_with('foo')? -
您可以尝试使用真正的 foo
self.foo = Foo(),然后模拟读取调用:self.foo.read = Mock()? -
或
patch.object可能是您正在寻找的stackoverflow.com/a/5044894/1389752 -
@SimeonVisser 你是对的。对于这个最小的例子,我忘记在我的测试中调用
a.act()。谢谢!我也更新了问题
标签: python python-2.7 unit-testing mocking python-unittest