Thursday, May 28, 2015

unit test private methods by creating private accessor

http://stackoverflow.com/questions/250692/how-do-you-unit-test-private-methods
It might not be usefull to test private methods. However, I also sometimes like to call private methods from test methods. Most of the time in order to prevent code duplication for test data generation...
Microsoft provides two mechanisms for this:
Accessors
  • Goto the class definition's source code
  • Right-click on the name of the class
  • Choose "Create Private Accessor"
  • Choose the project in which the accessor should be created => You will end up with a new class with the name foo_accessor. This class will be dynamically generated during compilation and privides all members public available.
However, the mechanism is sometimes a bit intractable when it comes to changes of the interface of the original class. So, most of the times I avoid using this.
PrivateObject class The other way is to use Microsoft.VisualStudio.TestTools.UnitTesting.PrivateObject
// Wrap an already existing instance
PrivateObject accessor = new PrivateObject( objectInstanceToBeWrapped );

// Retrieve a private field
MyReturnType accessiblePrivateField = (MyReturnType) accessor.GetField( "privateFieldName" );

// Call a private method
accessor.Invoke( "PrivateMethodName", new Object[] {/* ... */} );

No comments:

Post a Comment