Wednesday, March 09, 2011

How to test a class member that is not public using Visual Studio 2010 ?

There are various ways to test a Class member which is not public
  • By making the private members public of a class under test
  • Breaks the encapsulation principle
  • API is modified just for the sake of testing

  • By making the private members internal of a class under test and annotate the assembly with internalsVisibleTo attribute and you can read more about it at http://msdn.microsoft.com/en-us/library/0tke9fxk.aspx


    • Breaks the encapsulation principle
    • API is modified just for the sake of testing

  • Make the private members reachable through a public member of a class under test and test these public members


    • Breaks the encapsulation principle
    • API is modified just for the sake of testing

  • Use reflection to invoke the non public members of a class under test



  • Using reflection is abstracted in Visual Studio so we can use


    • PrivateObject to access non public Instance members of a class under test
    • PrivateType to access static members of a class under test
    These classes are inside Microsoft.VisualStudio.TestTools.UnitTesting namespace. I have created code snippets in Visual Studio 2010.CodeProject

    Read more: Daily .NET tips