开发者

Is it a right case for Mockito spy?

开发者 https://www.devze.com 2023-01-16 00:03 出处:网络
Let\'s say I have a class class SomeClass { public void methodA() {} public void methodB() {} public void someMethod()

Let's say I have a class

class SomeClass
{
  public void methodA()
  {}

  public void methodB()
  {}

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

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

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

Something like

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

I'm new to the mockito and documentation says

"Real spies should be used carefully and occasionally, for example when dealing with legacy code."

开发者_开发问答So maybe I'm missing something and there is better (right) way to verify that methodA and methodB were called without explicitly calling them in the test case.

Thanks.


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


If your code needs spy for unit testing - something wrong. Spy is a first sign of a code smell. You have two options to avoid it in your example:

  1. You can avoid mocking one of the method and test the whole someMethod.
  2. If methodA and methodB is really needs to be mocked - you can move them to seperate class etc.
0

精彩评论

暂无评论...
验证码 换一张
取 消