Chapter 53
Testing Private Members
One of the selling features of unit testing is that it is particularly effective for testing the internals of your class to ensure that they function correctly. The assumption here is that if each of your classes works in isolation, then there is a better chance that they will work together correctly; and in fact, unit testing can be used to test classes working together. However, you might be wondering how well the unit testing framework handles testing private methods.
One of the features of the .NET Framework is the capability to reflect over any type that has been loaded into memory and execute any member regardless of its accessibility. This functionality does come at a performance cost, however, as the reflection calls obviously include an additional level of redirection, which can prove costly if done frequently. Nonetheless, for testing, reflection enables you to call into the inner workings of a class and not worry about the potential performance penalties for making
those calls.
The other more significant issue with using reflection to access non-public members of a class is that the code to do so is somewhat messy. Luckily, Visual Studio 2005 does a very good job of generating a
wrapper class that makes testing even private methods easy. To show this, return to the CurrentStatus property and change its access from public to private. If you follow the same process you did previously to generate the test method for this property, you will see that an additional class is generated
to support the test method. The first snippet of the following code is the new test method that is generated (there may be naming differences if your Subscription class is in a different namespace from
DeveloperNews):
<TestMethod()> _
Public Sub PrivateCurrentStatusTest()
Dim target As Subscription = New Subscription
Dim val As Subscription.Status = Subscription.Status.Temporary
Dim accessor As DeveloperNews_SubscriptionAccessor = _
New DeveloperNews_SubscriptionAccessor(target)
Assert.AreEqual(val, accessor.CurrentStatus, _ “DeveloperNews.Subscription.CurrentStatus was not set correctly.”)
End Sub
As you can see, the preceding example uses an instance of the DeveloperNews_SubscriptionAccessor class to access the CurrentStatus property. In the test project is a new file, VSCodeGenAccessors.vb, which contains this class definition:
<System.Diagnostics.DebuggerStepThrough(), _ System.CodeDom.Compiler.GeneratedCodeAttribute _
(“Microsoft.VisualStudio.TestTools.UnitTestGeneration”, “1.0.0.0”)> _ Friend Class DeveloperNews_SubscriptionAccessor
Inherits BaseAccessor
Protected Shared m_privateType As PrivateType = _