gpt4 book ai didi

python - 如何使用 Python Mock 断言方法调用顺序?

转载 作者:太空狗 更新时间:2023-10-30 00:44:14 25 4
gpt4 key购买 nike

假设我有一个 python 函数

def func(self):
self.method_1()
self.method_2()

我如何编写一个单元测试来断言 method_1 在 method_2 之前被调用?

@mock.patch(method_1)
@mock.patch(method_2)
def test_call_order(method_2_mock, method_1_mock):
# Test the order

最佳答案

您的情况与 Python Unit Testing with two mock objects, how to verify call-order? 略有不同。 .您应该做的是将 method_2_mockmethod_1_mock 设置为一个新模拟对象的子对象,然后请求 mock_calls 属性或使用 assert_has_calls:

@mock.patch(method_1)
@mock.patch(method_2)
def test_call_order(method_2_mock, method_1_mock):
mock_parent = Mock()
mock_parent.m1, mock_parent.m2 = method_1_mock, method_2_mock
<test code>
"""Check if method 1 is called before method 2"""
mock_parent.assert_has_calls([call.m1(), call.m2()])

此代码中省略了很多细节,例如调用参数。看看call和非常有用的ANY helper 。

注意这仅对 python3 中的 unitetest.mock 有效。对于 python 2.7 和模拟 1.0.1,您应该改用 attach_mock

关于python - 如何使用 Python Mock 断言方法调用顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32463321/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com