Is this the right case for a Mockito spy?

Say I have a class

class SomeClass { public void methodA() {} public void methodB() {} public void someMethod() { methodA(); methodB(); } } 

I would like to check the behavior of someMethod () with Mockito.

The only way I could think of is to use spy ();

Something like

 SomeClass someClass = spy(new SomeClass()); someClass.someMethod(); InOrder inOrder = inOrder(someClass); inOrder.verify(someClass).methodA(); inOrder.verify(someClass).methodB(); 

I am new to mockito and the documentation says

"Real spies should be used carefully and sometimes, for example, when working with outdated code."

So maybe I missed something, and there is a better (correct) way to check if methods A and methodB are called without explicitly naming them in the test case.

Thanks.

+6
java unit-testing mockito
source share
2 answers

Yes, spy() is suitable for your purpose. The warning is due to the fact that real methods are called, and therefore, you can get unexpected results (for example, real money is withdrawn from a bank account)

+6
source share

If your code needs a spy for unit testing, then something is wrong. A spy is the first sign of code smell. You have two options to avoid this in your example:

  • You can avoid bullying one of the methods and test the entire someMethod method.
  • If method A and methodB really need to be mocked, you can move them to a separate class, etc.
-one
source share

All Articles