How do I test a private function or a class that has private methods, fields or inner classes?

Technology CommunityCategory: Software ArchitectureHow do I test a private function or a class that has private methods, fields or inner classes?
VietMX Staff asked 3 months ago

The best way to test a private method is via another public method. If this cannot be done, then one of the following conditions is true:

  1. The private method is dead code
  2. There is a design smell near the class that you are testing
  3. The method that you are trying to test should not be private

Also, by testing private methods you are testing the implementation. This defeats the purpose of unit testing, which is to test the inputs/outputs of a class’ contract. A test should only know enough about the implementation to mock the methods it calls on its dependencies. Nothing more. If you can not change your implementation without having to change a test – chances are that your test strategy is poor.