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

后端 未结 1 1965
无人共我
无人共我 2021-01-24 01:14

How do I check if bar(Alpha, Baz) called bar(Xray, Baz) using Mockito - without actually calling the later, given my MCVE class Foo:

相关标签:
1条回答
  • 2021-01-24 01:50

    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.

    0 讨论(0)
提交回复
热议问题