3

我第一次尝试使用 Python 模拟模块(使用 pip 下载)。我在设置断言时遇到问题,我已将其范围缩小到以下代码:

class TestUsingMock(unittest.TestCase):

    def setUp(self):
        self.fake_client = mock.Mock()

    def test_mock(self):
        self.fake_client.copy = mock.Mock()
        self.fake_client.copy("123")
        self.fake_client.assert_called_with("123")

if __name__ == "__main__":
    unittest.main()

这是我得到的错误:

F
======================================================================
FAIL: test_mock (__main__.TestVCSDriver)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "./mock_test.py", line 17, in test_mock
    self.fake_client.assert_called_with("123")
  File "/Library/Python/2.6/site-packages/mock.py", line 859, in assert_called_with
    raise AssertionError('Expected call: %s\nNot called' % (expected,))
AssertionError: Expected call: mock('123')
Not called

没有断言,一切正常。我究竟做错了什么?

4

1 回答 1

7

您正在调用该对象,但测试是否已调用self.fake_client.copy另一个对象。self.fake_client

要么调用“正确”的对象:

self.fake_client("123")
self.fake_client.assert_called_with("123")

或测试copy

self.fake_client.copy("123")
self.fake_client.copy.assert_called_with("123")
于 2012-06-01T09:50:55.243 回答