magicmock多次调用,但我无法断言

时间:2014-03-10 12:50:16

标签: python unit-testing mocking

(Python 2.6)

我有一个方法:

def send_all(self, messages):
    for message in messages:
        queue.send(message)

我想声明为每条消息调用queue.send()

queue = MagicMock()
myobj= MyObject(queue)
myobj.send_all(test_messages)
for test_message in test_messages:
    queue.send.assert_called_once_with(test_message)

test_messages中的55条消息中的每条消息都是唯一的。我收到以下错误:

AssertionError: Expected to be called once. Called 55 times.

1 个答案:

答案 0 :(得分:3)

assert_called_once_with()测试你的模拟是否只被调用;不要用它来测试55个不同的电话。

相反,声称这55个调用是使用mock.assert_has_calls()方法进行的:

queue.send.assert_has_calls([call(test_message) for test_message in test_messages])

这将测试是否存在55个呼叫的序列;它并没有限制模拟被多次调用。

您还可以测试mock.mock_calls attribute

assert queue.send.mock_calls == [call(test_message) for test_message in test_messages]

这将测试完全那55个电话。