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

时间:2017-08-08 13:55:07

标签: c++ testing

我知道在 Go 中,通常使用所谓的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)
    }
}
  

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

我非常喜欢这种 Go 样式来实现测试。所以我想知道,是否有可能在 C ++ 中使用与它类似的东西?如果有可能,你能告诉我一个例子吗?

编辑:我正在使用 Qt Creator ,我创建了一个类来执行单元测试。我真正想知道的是,是否可以使用输入输出创建结构,并迭代这些条目以执行每个测试。因为我使用Qt它不需要是'标准C ++结构',它可以是Qt提供的另一种数据结构。

1 个答案:

答案 0 :(得分:2)

这是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,大概是您想要的。