【问题标题】:How to test if a method is called using pytest如何使用pytest测试方法是否被调用
【发布时间】:2017-06-24 15:43:22
【问题描述】:

我想写一个单元测试来检查一个方法是否被调用。有没有办法做到这一点。或者我误解了在这里可以使用模拟的方式?因为这种方式总是调用 mocked_method 但没有任何参数。

@(pytest.parameterize)
def test(jsonrpc_proxy):
    jsonrpc_proxy.method1_call()
    # Method 1 should not call method 2
    with mock.patch('method2') as mocked_method:
        assert ((args),) not in mocked_track.call_args_list

    # do something 
    jsonrpc_proxy.method1_call()
    # Method 1 should call method 2
    with mock.patch('method2') as mocked_method:
        assert ((args),) in mocked_track.call_args_list

PS:在发布之前,我已经检查了与它相关的其他问题,但我认为我误解了我们如何在这种情况下使用模拟的整个概念。请赐教,因为我是新手。

【问题讨论】:

    标签: python django mocking pytest pytest-django


    【解决方案1】:

    您需要在修补method2 时调用method1,而不是在此之前。 尝试在 with 语句中移动调用:

    with mock.patch('method2') as mocked_method:
        jsonrpc_proxy.method1_call()
        assert ((args),) not in mocked_track.call_args_list
    

    【讨论】:

    • 通常最好使用mocked_method.assert_called_with(arguments...)断言定义的调用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多