Rajat Vij
Rajat Vij

Reputation: 367

How to test if a method is called using pytest

I want to write a unit test to check if a method is being called. Is there any way to do it. Or i am misunderstanding the way mock can be used here? As this way mocked_method is always called but without any args.

@(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: I have checked other questions related to it before posting, but i think i am misunderstanding the whole concept about how we use mock in such scenarios. Please enlighten me as i am new to this.

Upvotes: 4

Views: 9263

Answers (1)

DorElias
DorElias

Reputation: 2313

you need to call method1 when method2 is patched, not before that. try moving the call inside the with statement:

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

Upvotes: 3

Related Questions