简体   繁体   中英

Check Mockito method call verify()

I have a test in jUnit4:

@Mock
MyWebClient myWebClientMock;

@Test
public void testOnOpen() throws Exception {
    System.out.println("OnOpen");
    Session session = null;
    MyWebClient instance = new MyWebClient();
    instance.connectToWebSocket();

    instance.OnOpen(instance.getSession());
    Mockito.verify(myWebClientMock).sendPing();
}

In last row of the code I check did I call method sendPing() . I pretty sure this method is called inside of OnOpen() method:

@OnOpen
@Override
public void OnOpen(Session session) throws IOException {
    this.session = session;
    sendPing();
}

When I make debug I figured out it was really invoked. But why Mockito.verify(myWebClientMock).sendPing() doesn't pass ?

Because you didn't invoke sendPing on the mock, you invoked it on the object referenced by instance .

Are you testing MyWebClient ? Or are you testing some other component that uses MyWebClient and therefore have to mock MyWebClient ? In this case you seem to be testing a specific component, but mocking putting expectations on a mock. That doesn't make sense.

It looks to me like MyWebClient is the class under test it doesn't make sense that you would also mock it. You should be mocking any classes that collaborate with MyWebClient.

If you are testing the OnOpen method then you should be asserting that the session has been set correctly, and then also sendPing has done whatever it is supposed to do. If sendPing calls some other class then you could mock that and verify the interactions with it.

    @Test
    public void testOnOpen() throws Exception {
        System.out.println("OnOpen");

        MyWebClient instance = new MyWebClient();
        instance.connectToWebSocket();

        MyWebClient spy = Mockito.spy(instance);
        spy.OnOpen(instance.getSession());
        Mockito.verify(spy).sendPing();
    }

That works. Thanks for your tries.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM