Python mock类是如何工作的?

时间:2016-05-30 03:26:02

标签: python python-2.7 mocking python-mock

这是我有一个班级的例子:

发动机/ a.py

from thirdlib import TaskClient
class TaskWorker(object):
    def __init__(self):     
          self.task_client = TaskClient(xxx, xxx, xxx, xxx)

    def some_task(id, app):
        tasks = self.task_client.query(1,2,3,4)
        print "tasks: " tasks
        for task in tasks:
           do_something()

然后我想测试一下:

class ImporterTest(unittest.TestCase):
    def setUp(self):
        self.client_patcher = patch('engine.a.TMClient', autospec=True)
        self.client_mocked = self.client_patcher.start()
        self.worker = TaskWorker()

def tearDown(self):
    self.client_patcher.stop()

def test_task_return_empty(self):
    self.client_mocked.query.return_value = []
    value = self.worker.some_task(1, 'notcare')
    #self.assertFalse(value)
    #print self.client_mocked.mock_calls
    self.client_mocked.query.assert_called_with(1,2,3,4)     

使用query.assert_called_with,

,此测试将失败
 Tasks: <MagicMock name='TMClient().query()' id='139779549447120'>

Traceback (most recent call last):
 File "/home/xxx/lib/python2.7/site-packages/mock/mock.py", line 925, in assert_called_with
  raise AssertionError('Expected call: %s\nNot called' % (expected,))

AssertionError:预期的调用:查询(1,2,3,4) 不叫

预期打印&#34;任务:[]&#34;但不是,因为assert_called_with也失败了

0 个答案:

没有答案