How do you unit test private methods?

前端 未结 30 1827
无人及你
无人及你 2020-11-22 06:44

I\'m building a class library that will have some public & private methods. I want to be able to unit test the private methods (mostly while developing, but also it coul

30条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 07:43

    It might not be useful 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[] {/* ... */} );
    

提交回复
热议问题