单元测试具有许多私有方法的复杂类

lan*_*der 1 testing unit-testing dependency-injection mocking separation-of-concerns

我有一个类有一个公共方法和许多私有方法,这些方法根据传递给public方法的参数运行,所以我的代码看起来像:

public class SomeComplexClass
{
    IRepository _repository;

    public SomeComplexClass()
       this(new Repository())
    {
    }

    public SomeComplexClass(IRepository repository)
    {
        _repository = repository;
    }


    public List<int> SomeComplexCalcualation(int option)
    {
        var list = new List<int>();

        if (option == 1)
            list = CalculateOptionOne();
        else if (option == 2)
            list = CalculateOptionTwo();
        else if (option == 3)
            list = CalculateOptionThree();
        else if (option == 4)
            list = CalculateOptionFour();
        else if (option == 5)
            list = CalculateOptionFive();

        return list;
    }

    private List<int> CalculateOptionOne()
    {
        // Some calculation
    }

    private List<int> CalculateOptionTwo()
    {
        // Some calculation
    }

    private List<int> CalculateOptionThree()
    {
        // Some calculation
    }

    private List<int> CalculateOptionFour()
    {
        // Some calculation
    }

    private List<int> CalculateOptionFive()
    {
        // Some calculation
    }
}
Run Code Online (Sandbox Code Playgroud)

我已经想到了几种测试这个类的方法,但是所有这些方法看起来都过于复杂,或者比我想要的更多地暴露方法.到目前为止的选项是:

  • 将所有私有方法设置为internal并使用[assembly:InternalsVisibleTo()]

  • 将所有私有方法分离到单独的类中并创建接口.

  • 使所有方法都是虚拟的,并在我的测试中创建一个继承自该类的新类并覆盖这些方法.

是否还有其他测试上述课程的选项会比我列出的更好?

如果您选择我列出的其中一个,您可以解释原因吗?

谢谢

Mar*_*ers 7

您无需更改界面即可测试这些方法.只需彻底测试公共接口,确保测试所有私有方法:

 void Test1() 
 {
      new SomeComplexClass(foo).SomeComplexCalcualation(1);
 } 

 void Test2() 
 {
      new SomeComplexClass(foo).SomeComplexCalcualation(2);
 } 
Run Code Online (Sandbox Code Playgroud)

等等...

您可以使用覆盖工具(例如NCover for .NET)来确保您要测试的所有代码都已经过测试.