代码之家  ›  专栏  ›  技术社区  ›  KelvinS Karel Petranek

我可以在C++中使用TableDrivenTests概念吗?

  •  0
  • KelvinS Karel Petranek  · 技术社区  · 8 年前

    我知道这一点 TableDrivenTests 要实现测试用例,例如:

    func TestMyFunc(t *testing.T) {
        var tTable = []struct {
            input  []float64
            result float64
        }{
            {[]float64{1, 2, 3, 4, 5, 6, 7, 8, 9}, 102.896},
            {[]float64{1, 1, 1, 1, 1, 1, 1, 1, 1}, 576.0},
            {[]float64{9, 9, 9, 9, 9, 9, 9, 9, 9}, 0.0},
        }
    
        for _, pair := range tTable {
            result := MyFunc(pair.input)
            assert.Equal(t, pair.result, result)
        }
    }
    

    给定一个测试用例表,实际测试只需迭代 所有表条目和每个条目都执行必要的测试。

    我真的很喜欢这个 C++ ? 如果可能的话,你能给我举个例子吗?

    :我正在使用 Qt创建者 输入 并遍历条目以执行每个测试。当我使用Qt时,它不需要是“标准C++结构”,它可以是Qt提供的另一种数据结构。

    1 回复  |  直到 8 年前
        1
  •  2
  •   Kane    8 年前

    下面是C++的1:1翻译:

    #include <vector>
    #include <iostream>
    
    // Testable function.
    double MyFunc(const std::vector<double> &input)
    {
        static double results[] = { 102.896, 576.0, 0.0 };
        static int i = 0;
        return results[i++]; // return different results
    }
    
    // Our test. Returns true if passes.
    bool TestMyFunc()
    {
        struct
        {
            std::vector<double> input;
            double result;
        } tTable[] =
        {
            {{1, 2, 3, 4, 5, 6, 7, 8, 9}, 102.896},
            {{1, 1, 1, 1, 1, 1, 1, 1, 1}, 576.0},
            {{9, 9, 9, 9, 9, 9, 9, 9, 9}, 0.0},
        };
    
        for ( const auto &pair : tTable ) {
            auto result = MyFunc(pair.input);
            if ( result != pair.result )
                return false; // return false if test fails
        }
    
        return true; // all test cases passed
    }
    
    int main() {
        std::cout << TestMyFunc() << std::endl;
        return 0;
    }
    

    gtest 有一个概念 value parametrised tests