How do you unit test private methods?

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 could be useful for future refactoring).

What is the correct way to do this?


如果您使用.net,则应使用InternalsVisibleToAttribute。


If you want to unit test a private method, something may be wrong. Unit tests are (generally speaking) meant to test the interface of a class, meaning its public (and protected) methods. You can of course "hack" a solution to this (even if just by making the methods public), but you may also want to consider:

  • If the method you'd like to test is really worth testing, it may be worth to move it into its own class.
  • Add more tests to the public methods that call the private method, testing the private method's functionality. (As the commentators indicated, you should only do this if these private methods's functionality is really a part in with the public interface. If they actually perform functions that are hidden from the user (ie the unit test), this is probably bad).

  • 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[] {/* ... */} );
    
    链接地址: http://www.djcxy.com/p/21404.html

    上一篇: 用于TDD的JavaScript单元测试工具

    下一篇: 你如何测试私有方法?