简体   繁体   English

正确的方法来模拟类和断言对方法的调用

[英]Proper way to mock classes and assert on calls to methods

I am trying to write unit tests for Bar that makes calls to Foo 's method read() . 我正在尝试为Bar调用单元测试来调用Foo的方法read() I have added the patch command in setUp() because other tests will use this patch as well. 我在setUp()添加了patch命令,因为其他测试也会使用此补丁。

Question

How can I check that the read() function was called with the arguments that I am expecting? 如何检查read()函数是否使用我期望的参数调用?

Code

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')

Output 产量

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)

read is a method on instances of Foo . readFoo 实例的一种方法。 You want to check for the mock return_value to access the instance. 您想检查模拟return_value以访问实例。 After all, you create the instance by calling foo.Foo() : 毕竟,您通过调用 foo.Foo()创建实例:

foo_instance = self.foo_mock.return_value
foo_instance.read.assert_called_once_with('foo')

Note that you are patching foo.Foo ; 请注意,您正在修补foo.Foo ; using bar.foo.Foo is the same object, but a round-about way of specifying it. 使用bar.foo.Foo是同一个对象,但是用于指定它的循环方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM