测试 mock 是否被其他 mock 调用

Testing if mock was called with other mock

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

@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 调用的正确方法是什么?

您的代码调用了 CredentialsMock 模拟对象,大概是为了创建一个实例。请注意结果名称中的 ()

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

当您只传入模拟本身时:

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

测试 return_value 结果:

XeroMock.assert_called_with(CredentialsMock.return_value)