代码之家  ›  专栏  ›  技术社区  ›  pencilCake

将testsettings参数注入方法以使其(单元或集成)可测试是一个好主意吗?

  •  1
  • pencilCake  · 技术社区  · 14 年前

    引入一个testsettings类以提供一个内部有许多进程的方法的灵活测试可能性,这是一个好的实践吗?

    也许不是一个很好的例子,但可以很简单:假设我有这个方法,我想测试它的子流程:

    public void TheBigMethod(myMethodParameters parameter)
    {
    
      if(parameter.Condition1)
       {
         MethodForCondition1("BigMac"); 
       }
    
      if(parameter.Condition2)
       {
         MethodForCondition2("MilkShake"); 
       }
    
      if(parameter.Condition3)
       {
         MethodForCondition3("Coke"); 
       }
    
      SomeCommonMethod1('A');
      SomeCommonMethod2('B');
      SomeCommonMethod3('C');
    }
    

    想象一下我对所有人都进行了单元测试

    • void MethodForCondition1(字符串)
    • void MethodForCondition2(字符串)
    • void MethodForCondition3(字符串)
    • void somecommonmethod1(char c)
    • void somecommonmethod2(char c)
    • void somecommonmethod3(char c)

    现在,我想通过引入这些测试方法和其中所需的断言来测试这个方法本身:

    • 条件1测试用例的样本方法
    • 条件2的色素方法
    • 条件3测试案例的方法
    • 一种共同的方法一种测试案例
    • 色素方法学
    • 色素方法学

    所以,我想让这种方法 退出能力 在某些时候,如果它被我上面的一个集成测试调用。

    public void TheBigMethod(myMethodParameters parameter, TestSettings setting)
    {
    
      if(parameter.Condition1)
       {
         MethodForCondition1("BigMac"); 
    
         if(setting.ExitAfter_MethodForCondition1)
            return;
    
       }
    
      if(parameter.Condition2)
       {
         MethodForCondition2("MilkShake"); 
    
         if(setting.ExitAfter_MethodForCondition2)
            return;
    
       }
    
      if(parameter.Condition3)
       {
         MethodForCondition3("Coke"); 
    
         if(setting.ExitAfter_MethodForCondition3)
            return;
    
       }
    
      SomeCommonMethod1('A');
      if(setting.ExitAfter_SomeCommonMethod1)
           return;
    
      SomeCommonMethod2('B');
      if(setting.ExitAfter_SomeCommonMethod2)
           return;
    
      SomeCommonMethod3('C');
      if(setting.ExitAfter_SomeCommonMethod3)
           return;
    }
    

    尽管它看起来像是在做我需要引入的测试设置参数,但是它会使代码的可读性变差,并且将测试逻辑和主要功能结合在一起也不好看。

    您能为这样的情况建议一个更好的设计,以便它可以替换测试设置参数的想法吗?

    谢谢

    2 回复  |  直到 14 年前
        1
  •  2
  •   Michael Lloyd Lee mlk    14 年前

    添加这个测试设置是一件非常糟糕的事情。另一种选择是为methodForCondition添加一个接口(或一组接口)。 X 还有一些常见的方法 X . 测试每个方法的条件 X &某些常用方法(amp;S) X 单独传递并传递一个用于验证该methodForCondition的方法的存根 X 使用值Z调用。

    编辑 :如果不想使用接口,也可以使这些方法成为虚拟的。

        2
  •  2
  •   Chris Knight    14 年前

    这里的游戏有点晚了,但我同意混合测试和生产代码是一种需要避免的大代码味道。遗留代码中的大方法提供了各种各样的问题。我强烈推荐你读迈克尔·费瑟的 Working Effectively with Legacy Code . 这一切都是关于处理遗留代码中遇到的无数问题以及如何处理它们。