Verifying sequence of private method calls in unit

2019-02-28 13:36发布

问题:

I have the following class:

class MyClass {

  public void doIt() {
     methodOne();
     methodTwo();
     methodThree();
  }

  private void methodOne() {
     // ...
  }

  // rest of methods similar...

}

My intention is to verify that when i invoke doIt(), methods metodOne(), methodTwo() and methodThree() will be invoked, in that order.

I'm using mockito for mocking. Does anyone knows how i can test this scenario?

回答1:

Hate to be the person but: simply don't test this. Test the output, side effects, results - not the implementation.

If you really want to ensure the correct order, extract these methods into separate class(es) and mock them.



回答2:

As long as your private methods are ... well ... private, don't test them. They are implementation details. They could be refactored without changing the contract of your class. Test the correct outcome of your public methods.