如何在模拟对象中断言一个方法?

时间:2015-08-27 18:59:54

标签: python unit-testing mocking

我是一个学习python模拟器,并且有问题来检查是否已经调用了模拟对象上的方法。

我要测试的代码是:

def main(flags, directory_service):
  if flags.has_schema:
    directory_service.HasSchema(SCHEMA_NAME)
    sys.exit(1)

我的测试代码是:

def testHaltsAfterCheckingSchema(self):
  mock_flags = self._CreateDefaultFlags()
  mock_flags.has_schema = True
  mock_directory_service = MagicMock()

  with self.assertRaises(SystemExit) as cm:
    key_distributor.main(mock_flags, mock_directory_service)
  self.assertTrue(mock_directory_service.HasSchema.assert_called_with(key_distributor.SCHEMA_NAME))
  self.assertEqual(cm.exception.code, 1)

当我运行它时,我得到了这个例外:

FAIL: testHaltsAfterCheckingSchema (test123.Test123)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test123.py", line 34, in testHaltsAfterCheckingSchema
    self.assertTrue(mock_directory_service.HasSchema.assert_called_with(key_distributor.SCHEMA_NAME))
AssertionError: None is not true

1 个答案:

答案 0 :(得分:6)

assert_called_with直接执行断言,并返回None。您根本不需要使用TestCase.assertTrue()

换句话说,以下就足够了:

mock_directory_service.HasSchema.assert_called_with(key_distributor.SCHEMA_NAME)

如果此断言失败(即directory_service.HasSchema()未被调用或使用不同的参数调用),那么assert_called_with会引发AssertError exceptionTestCase会抓住您并记录为测试失败:

>>> from unittest.mock import MagicMock
>>> mock_directory_service = MagicMock()
>>> mock_directory_service.HasSchema('SCHEMA_NAME')
<MagicMock name='mock.HasSchema()' id='4562465232'>
>>> mock_directory_service.HasSchema.assert_called_with('SCHEMA_NAME')
>>> mock_directory_service.HasSchema.assert_called_with('foobar')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python3.4/unittest/mock.py", line 771, in assert_called_with
    raise AssertionError(_error_message()) from cause
AssertionError: Expected call: HasSchema('foobar')
Actual call: HasSchema('SCHEMA_NAME')