简体   繁体   English

检查Mockito方法调用verify()

[英]Check Mockito method call verify()

I have a test in jUnit4: 我在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() . 在代码的最后一行,我检查是否调用了sendPing()方法。 I pretty sure this method is called inside of OnOpen() method: 我很确定此方法在OnOpen()方法内部被调用:

@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 ? 但是,为什么Mockito.verify(myWebClientMock).sendPing()没有通过?

Because you didn't invoke sendPing on the mock, you invoked it on the object referenced by instance . 因为您没有在模拟中调用sendPing ,所以您在instance引用的对象上调用了它。

Are you testing MyWebClient ? 您正在测试MyWebClient吗? Or are you testing some other component that uses MyWebClient and therefore have to mock MyWebClient ? 还是您正在测试使用MyWebClient其他组件,因此必须模拟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. 在我看来,MyWebClient是受测试的类,您也可以对其进行模拟是没有道理的。 You should be mocking any classes that collaborate with MyWebClient. 您应该嘲笑与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. 如果要测试OnOpen方法,则应该断言会话已正确设置,然后sendPing也已完成了应做的任何事情。 If sendPing calls some other class then you could mock that and verify the interactions with it. 如果sendPing调用其他某个类,则可以对此进行模拟并验证与之的交互。

    @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. 感谢您的尝试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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