简体   繁体   English

在Python中的简单模拟上,AssertionError“未调用”

[英]AssertionError “not called” on simple mock in Python

I'm trying to use the Python mock module (downloaded using pip) for the first time. 我第一次尝试使用Python模拟模块(使用pip下载)。 I'm having problems setting an assert, I've narrowed it down to this code: 我在设置断言时遇到问题,我已将其缩小到此代码:

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

This is the error I get: 这是我得到的错误:

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

Without the assertion, everything works fine. 没有断言,一切正常。 What am I doing wrong? 我究竟做错了什么?

You are calling the object self.fake_client.copy , but test whether another one, self.fake_client has been called. 您正在调用self.fake_client.copy对象,但测试是否已调用另一个self.fake_client

Either call the "correct" object: 要么调用“正确”的对象:

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

or test the copy : 或测试copy

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

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

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