How would you unit test private methods?

Technology CommunityCategory: TestingHow would you unit test private methods?
VietMX Staff asked 3 years ago

If you want to unit test a private method, something may be wrong. Unit tests are (generally speaking) meant to test the interface of a class, meaning its public (and protected) methods. You can of course “hack” a solution to this (even if just by making the methods public), but you may also want to consider:

  1. If the method you’d like to test is really worth testing, it may be worth to move it into its own class.
  2. Add more tests to the public methods that call the private method, testing the private method’s functionality. (As the commentators indicated, you should only do this if these private methods’s functionality is really a part in with the public interface. If they actually perform functions that are hidden from the user (i.e. the unit test), this is probably bad).