I'm studing TDD and recently searching for how to unit test private method properly. Popular answers in Stack Overflow were suggesting:
- Use reflection to make private methods accessable from outside. 1
- Do not test private methods. (Use public methods instead.) 1 2 3
According to disagreements in comment section, it seems everyone have their own rules. Then I found this tutorial site that suggests a rather bold approach.
- Make
private
methodprotected
orpackage private
. Put test codes in the same package.Designing for testability means designing your code so that it is easier to test. To do so, you may have to break with some of the principles we learned in university, like encapsulation.
Even though TDD's principle is designing codes for testability, breaking encapsulation for that doesn't sound right for me. Is this approach a good prectice?