Unit Testing Private Methods

xiaoxiao2021-03-06  101

Unit Testing Private Methods

Projects that use nUnit extensively often debate whether or not to test private methods. As one of our developers wrote, "In old C world we used to use 'friend' keyword to allow class FooTest to access ALL methods and fields of class Foo. This Allowed US to Perform 'White Box' Testing By Verifying Internal Class State. This Level of Testing is preformed companies. ""

A similiar result could be achieved in C # by having the unit tests build into the same assembly as the classes they are testing and then to declare methods as 'protected internal' instead of protected and 'internal' instead of private. By using a multi- file assembly (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconbuildingmulti-fileassembly.asp) the tests can be in a seperate dll, and still access The INTERNAL METHODS OF THE Business Objects.

However, Visual Studio does not offer good support for multifile assemblies. Multifile assemblies must be linked with the command-line Assembly Linker, which makes build scripts and processes more complex.

I suggest what tests surplend be written only for the public method. This Offers Several Advantages:

Users will use the public methods, so all functionality should be exposed there -. If there is code that does not affect a public method, you should take it out Writing the tests against the interface improves the interface -.. Users of the class have to program against the interface, if it is not clear and easy to use, improve the interface. If you write tests against private methods, you may never notice that you do not have a public interface to perform some action. Tests are not tied to the internals of a class -. If tests only test the public functionality, they will not have to be rewritten during performance tuning or other optimizations If the tests are written against an interface, other classes that implement the same interface can be Tested without Changing The Tests.posted on Wednesday, December 31, 2003 3:36 PM

FEEDBACK

#

Re: Unit Testing Private Methods

StevePosted @ 12/31/2003 4:22 PMI've taken the approach you mentioned. I test the public interface to ensure the components do what I expect. Usually if something's wrong in one of the private methods the test for the public method " Catches "The Error.

#

Re: Unit Testing Private Methods

OMER VAN KLOETENPOSTED @ 1/1/2004 7:41 AMHTTP: //weblogs.asp.net/okloeten/archive/2003/11/35176.aspx#feedback

#

Re: Unit Testing Private Methods

转载请注明原文地址:https://www.9cbs.com/read-125566.html

New Post(0)