1

我试图更好地理解这三个原则。

我的问题是……如何在不违反 SRP、OCP 和 DRY 的情况下编写测试?

由于测试文件中的代码相似,我当前的设计违反了 DRY。

我无法将测试文件合并在一起,因为这将违反打开/关闭原则。(以后增加更多模块的概率很大)

我在这里缺少什么吗?如果有帮助,我正在为此使用 Ruby 和 Minitest。

模块文件

a.rb:

module A
  # does an algorithm
end

b.rb:

module B
  #does another algorithm
end

测试文件

a_test.rb:

class ModuleATest
  # tests the algorithm
end

b_test.rb:

class ModuleBTest
  # tests the algorithm
end
4

2 回答 2

0

这是我的做法。OCP:测试模块的类不必修改 SRP:这些类只测试模块 DRY:通过创建包含模块测试器,您可以避免测试中的代码重复。

module A
    def algorithm(foo)
        #some implementation 
    end
end

module B
    def algorithm(foo)
        #some implementation    
    end
end

module Module_Tester
    def test_module_test
        assert_equal(@expected, @obj.algorithm(@to_test))
        # you test them
    end
end


class ModuleATest < test_framework
    include Module_Tester
    def before 
        @obj = Object.new.extend(A)
        @expected = 'Expected Outcome goes here'
        @to_test = 'The thing to test goes here'
    end
end

class ModuleBTest < test_framework
    include Module_Tester

    def before
        @obj = Object.new.extend(B)
        @expected = 'The Expected Outcome'
        @to_test = 'The thing to test'
    end
end
于 2015-11-03T15:35:53.300 回答
0

测试代码与常规代码完全不同,因此尽管所有这些设计原则在测试代码中通常都有效,但它们的重要性是不同的。

关于 DRY,测试代码首先需要可读性,因此测试代码中的重复比常规代码多一点是正常的。听起来测试您的两种算法中的每一种都需要您没有显示的重复;通过将重复提取到测试辅助方法中来解决这个问题。但只有在保持测试的清晰性时才这样做。

关于 OCP,测试需要做它需要做的任何事情来测试它正在测试的模块。如果一开始你的模块设计错误并且不得不将一个模块分成两个或其他东西,那么你必须对测试做同样的事情。所以不要担心你的测试是否遵循 OCP,担心你的常规代码和测试会遵循。

关于 SRP,再次,测试需要做它需要做的任何事情来测试它正在测试的模块。如果一个模块有太多的职责,那么它的测试也会如此。这表明模块需要重构以解决模块和测试的问题。

此外,还有不同类型的测试。就其本质而言,集成测试比单元测试承担更多的责任。

于 2016-02-08T14:41:25.257 回答