模拟类并在对方法的调用中进行断言的正确方法

jay*_*ant 4 python unit-testing mocking python-2.7 python-unittest

我正在尝试编写单元测试,Bar以便Foo对的方法进行调用read()。我添加了patch命令,setUp()因为其他测试也将使用此补丁。

如何检查该read()函数是否已使用期望的参数调用?

foo.py
class Foo(object):
    def __init__(self):
        self.table = {'foo': 1}

    def read(self, name):
        return self.table[name]
Run Code Online (Sandbox Code Playgroud) bar.py
import foo

class Bar(object):
    def act(self):
        a = foo.Foo()
        return a.read('foo')
Run Code Online (Sandbox Code Playgroud) 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')
Run Code Online (Sandbox Code Playgroud)

输出量

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)
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 5

read是对的实例的方法Foo。您要检查模拟return_value以访问实例。毕竟,您可以通过调用来 创建实例foo.Foo()

foo_instance = self.foo_mock.return_value
foo_instance.read.assert_called_once_with('foo')
Run Code Online (Sandbox Code Playgroud)

注意您正在打补丁foo.Foo;using bar.foo.Foo是相同的对象,但是指定它的一种绕过方式。