How do I verify the number of invocations of overloaded method using Mockito?

╄→гoц情女王★ 提交于 2019-12-02 05:30:25

You don't need to do this.

The reason this is driving you nuts is that you aren't using Mockito the way it is intended to be used. It can be used this way, but it should not be.

You don't need to test that the right method was called, you need to test that the behavior of your class is correct. What does that mean?

  1. You want to check that "Xray" was returned.

    String result = foo.bar(alpha, baz);
    assertEquals("Xray", result);
    
  2. You want to check that Alpha.get was called. If anything, this means that Alpha should be the stub, not Foo.

    Alpha alpha = spy(new Alpha());
    String result = foo.bar(alpha, baz);
    verify(alpha).get();
    

The bottom line is this: You have your System Under Test, in this case Foo. That class should be a real class. Your mocks and stubs should be the other objects that interact with Foo; verify that the interactions do the correct things.

In other words, you shouldn't be testing how Foo works, you should be testing that Foo does what it's supposed to do; that the results are correct.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!