测试是否使用其他模拟调用了mock

时间:2017-02-12 22:50:04

标签: python unit-testing mocking python-unittest

我正在尝试测试是否使用另一个模拟对象调用了模拟对象。

@patch(__name__ + '.xero_helper.PublicCredentials')
@patch(__name__ + '.xero_helper.Xero')
def testGetValidPublicXeroInstance(self, XeroMock, CredentialsMock):
    xero_helper.get_xero_instance('abc')  # Do relevant stuff

    CredentialsMock.assert_called_with(**org.oauth_credentials)  # OK
    XeroMock.assert_called_once()  # OK
    XeroMock.assert_called_with(CredentialsMock)  # Not OK

前两个assert传球,而最后一个传球

AssertionError: Expected call: Xero(<MagicMock name='PublicCredentials' id='4377636560'>)
Actual call: Xero(<MagicMock name='PublicCredentials()' id='4377382544'>)

验证使用XeroMock调用CredentialsMock的正确方法是什么?

1 个答案:

答案 0 :(得分:3)

您的代码称为 CredentialsMock模拟对象,可能是为了创建实例。请注意结果名称中的()

<MagicMock name='PublicCredentials()' id='4377382544'>
#                                 ^^ called

当你传入模拟本身时:

<MagicMock name='PublicCredentials' id='4377636560'>
#                                ^ not called

测试return_value结果:

XeroMock.assert_called_with(CredentialsMock.return_value)