【问题标题】:Unit test: How to assert multiple calls of same method?单元测试:如何断言同一方法的多个调用?
【发布时间】:2013-11-28 16:31:16
【问题描述】:

我有一个方法,它用不同的参数调用另一个方法两次。

class A(object):
    def helper(self, arg_one, arg_two):
        """Return something which depends on arguments."""

    def caller(self):
        value_1 = self.helper(foo, bar)  # First call.
        value_2 = self.helper(foo_bar, bar_foo)  # Second call!

使用assert_called_with 可以帮助我只断言第一个调用,而不是第二个调用。即使assert_called_once_with 似乎也没有帮助。我在这里想念什么?有什么方法可以测试这样的调用吗?

【问题讨论】:

    标签: python unit-testing python-unittest


    【解决方案1】:

    您可以使用mock_calls,其中包含对方法的所有调用。此列表包含第一次调用、第二次调用以及所有后续调用。因此,您可以使用mock_calls[1] 编写断言来说明有关第二次调用的内容。


    例如,如果m = mock.Mock() 并且代码执行m.method(123),那么您编写:

    assert m.method.mock_calls == [mock.call(123)]
    

    它断言对m.method 的调用列表恰好是一个调用,即带有参数123 的调用。

    【讨论】:

    • 他们文档中的示例没有多大意义。你能举一个更好的例子吗?
    • @BrandonIbbotson 我在上面的答案中添加了一个示例。
    【解决方案2】:

    要添加到 Simon Visser 的答案,您可以使用 unittest.TestCase self.assertEqual() 方法而不是 assert 语法,我认为这是单元测试上下文中更好的做法,因为您还可以将 cmets 添加到它会在出现问题时显示。

    例如:

    self.assertEqual(
        [
            mock.call(1, 'ValueA', True)),
            mock.call(2, 'ValueB', False)),
            mock.call(3, 'ValueC', False))
        ],
        mock_cur.execute.mock_calls,
        "The method was not called with the correct arguments."
    ) 
    

    【讨论】:

      猜你喜欢
      • 2011-04-19
      • 1970-01-01
      • 2013-08-03
      • 1970-01-01
      • 1970-01-01
      • 2013-03-18
      • 1970-01-01
      • 1970-01-01
      • 2011-02-22
      相关资源
      最近更新 更多