Thursday, April 24, 2008

Unit Testing private members of the class using VSTE for Testers

By default unit tests will not have access to private members of the class. However this can be done with the help of Reflection. VSTS has a class PrivateObject which can help you do this. This class does all the required plumbing and gives you a straight forward approach to deal with this problem.

Following are the steps to use the PrivateObject class.

1. Instantiate the PrivateObject class by providing the “typeof” class to be tested. The best place to do this is the TestInitialize method.
2. Now you can access the private field of the class using the GetField method on the PrivateObject instance.
3. Similarly you can test the private method of the class using the Invoke method of the PrivateObject. This can be best done in a separate test method.

In a similar way you can access the static-private members of your test class using the PrivateType class

No comments: