unit-testing - 单元测试具有许多私有(private)方法的复杂类

标签 unit-testing testing dependency-injection mocking separation-of-concerns

我有一个带有一个公共(public)方法和许多私有(private)方法的类,这些方法的运行取决于传递给公共(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
    }
}

我想过几种方法来测试这个类,但所有这些方法似乎都过于复杂,或者公开的方法比我想要的要多。到目前为止的选项是:

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

  • 将所有私有(private)方法分离到一个单独的类中并创建一个接口(interface)。

  • 使所有方法成为虚拟方法,并在我的测试中创建一个继承此类的新类并覆盖这些方法。

是否有任何其他选项可以比我列出的更好地测试上述类?

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

谢谢

最佳答案

您无需更改界面即可测试这些方法。简单地彻底测试公共(public)接口(interface)以确保测试所有私有(private)方法:

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

 void Test2() 
 {
      new SomeComplexClass(foo).SomeComplexCalcualation(2);
 } 

等等……

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

关于unit-testing - 单元测试具有许多私有(private)方法的复杂类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2738628/

相关文章:

python - Django 单元测试和模拟请求模块

c++ - 用 Boost::Test 模拟

c# - 断言比较两个对象列表 C#

c++ - 在 googletest 中循环测试用例

django - 如何在测试 Django 时禁用 csrf?

go - 嵌套依赖注入(inject)在 golang 中是否可以接受?

javascript - 单元测试、使用 JS 的数据库方法

testing - 服务器的 "skipUncaughtErrors"标志是什么意思?

spring - AnnotatedElementUtils错误 Spring 测试

javascript - 缩小 httpInterceptor AngularJS $injector 错误