如何使用pytest测试方法是否被调用

How to test if a method is called using pytest

我想编写一个单元测试来检查是否正在调用某个方法。有什么办法吗。或者我误解了这里可以使用 mock 的方式?这样 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:我在发帖前检查了其他相关问题,但我想我误解了我们在这种情况下如何使用 mock 的整个概念。请赐教,因为我是新手。

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

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