How do you unit test private methods?

前端 未结 30 1492
无人及你
无人及你 2020-11-22 06:44

I\'m building a class library that will have some public & private methods. I want to be able to unit test the private methods (mostly while developing, but also it coul

30条回答
  •  醉酒成梦
    2020-11-22 07:31

    1) If you have a legacy code then the only way to test private methods is by reflection.

    2) If it is new code then you have the following options:

    • Use reflection (to complicated)
    • Write unit test in the same class (makes the production code ugly by having test code also in it)
    • Refactor and make the method public in some kind of util class
    • Use @VisibleForTesting annotation and remove private

    I prefer the annotation method, simplest and least complicated. The only issue is that we have increased the visibility which I think is not a big concern. We should always be coding to interface, so if we have an interface MyService and an implementation MyServiceImpl then we can have the corresponding test classes that is MyServiceTest (test interface methods) and MyServiceImplTest (test private methods). All clients should anyway be using the interface so in a way even though the visibility of the private method has been increased it should not really matter.

提交回复
热议问题