Hanging out on infoq today, I found a group of people discussing whether to write unit tests for private methods. of course, there is nothing new. the Support Team said that unit testing requires a small granularity of test, and private methods may be very complex and cannot be fully tested using public APIs. the opposing party said that the private method does not need to be tested because it is invisible to the outside world and TDD only needs Code After testing, you can rebuild the private method if it is too complex.
In the end, I saw a reply, which is quite moderate. Basically, do not write unit tests for private methods. If you need to write them, first make it clear, why should we set this method to private instead of public. in the end, some private methods with exceptions need to be tested in units. Method injection can be used. The steps are excerpted as follows:
1) you create an inner class within the class under test-call it testprobe
2) you create an accessor to that probe in the parent class-something like gettestprobe ()
3)
Because the inner class has access to all the private methods and
Variables, you can add as your getters/setters as you want to fudge
With the inner state of the class under test.
4) You get to keep
Parent class's original private variables and methods and minimally
Modify it's public interface by adding one getter: gettestprobe ().
An example of a testprobe might look something like this: Public Class Foo {
Private Map cache;
Private Int Itemsincachematching (string pattern) {}
/**/ /** For tests only. Not to be used by production code.*/
Public Class Testprobe {
Public Map cache () {ReturnCache ;}
Public Int Itemsincachematching (string pattern) {
ReturnFoo.This. Itemsincachematching (pattern );
}
}
}