Do you want to write unit test for private method?

Source: Internet
Author: User
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 );
}
}

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.