Mocking ScheduledExecutorService vs the “Don't mock type you don't own” philosophy

后端 未结 2 1699
既然无缘
既然无缘 2021-01-22 11:28

Mocking ScheduledExecutorService would really make testing my classes easier, but according to the mockito recommendations this seems a bad idea, as the logic of the mocked clas

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-22 12:03

    I'd say the "Don't mock type you don't own!" is the false conclusion out of the right reasoning.

    Unittests should only need to be changes if your API changes or the part of an API of a dependency your code uses.

    example:

    You us an interface of a dependency as an input parameter, but your tested code uses only one method in that interface. If you don't mock this interface (which is a type you don't own) you have to create your own dummy implementation implementing all of the interfaces methods, even those you don't use.

    If you change the version of that dependency this interface might have additional method and/or some methods have been removed. You have to change all of your the implementations of this interface throughout your program. If you mocked this interface you don't need to change your tests and they still give you confidence that your codes behavior did not change after the required refactoring.

    Furthermore your Unittest should only fail because the behavior of your code changed, not because of a change in the dependencies behavior. Changes in a dependencies behavior should be pinned with separate Unittest you setup for the dependencies behavior (if it is crucial for your application) and/or integration tests.

提交回复
热议问题