表达式:VS2015单元测试框架中向量测试的范围外错误

Expression: Out of Range Error with vector tests in VS2015 unit test framework

本文关键字:测试 范围 错误 向量 VS2015 单元测试 框架 表达式      更新时间:2023-10-16

我正在基于Microsoft的本机框架构建一组基于Visual Studio 2015的单元测试。我正在使用下面显示的代码,它编译和运行都没有问题。然而,当我运行测试时,它会抛出一个错误(下面是完整消息)。在drawGraph之前,调用一个例程,将历史初始化为等于float Data[15][5],然后用15个5的数组完全填充。我做错了什么?

vector< vector<float> > history;
float drawGraph(float graph[4][10]) {
    float m, c, j, x1, x2;
    int i = 0;
    while (i < history.size() - 1) {
        j = i + 1;
        x1 = history[i][0];
        x2 = history[j][0];
        m = history[j][3] / history[j][2];
        c = history[i][1] - m*x2;
        i++;
        graph[0][i] = { x1 };
        graph[1][i] = { x2 };
        graph[2][i] = { m };
        graph[3][i] = { c };
    }
    return graph[0][0];
};

这是我的测试代码:

TEST_METHOD(Graph_Equations_Correct) {
    float graph[4][10];
    int i = 1;
    while (i < 10) {
        drawGraph(graph);
        Assert::AreEqual(history[i][4], graph[2][i]);
        i++;
    }
}

这是它抛出的结果/错误:

结果StackTrace:在c:\program files(x86)\microsoft visual studio 14.0\vc\include\vector:line 1233中的std::vector>::运算符在c:\users\george\documents\history testing 2\UnitTest1\UnitTest1.cpp:行32中的UnitTest1::MyTests::Graph_Equations_Correct()结果消息:在函数std::vector>:operator[],c:\program files(x86)\microsoft visual studio 14.0\vc\include\vector line 1233中检测到无效参数。表达式:"超出范围"

编辑:

我调用的第一个测试是:

TEST_METHOD(Array_Populates)
{
    int i = 0;
    while (i < 10) {
        populateArray(dummyData[i][0], dummyData[i][1]);
        //Assert::AreEqual(history[i][0], dummyData[i][1]);
        i++;
    }
    int j = 0;
    while (j < history.size()) {
        Assert::AreEqual(dummyData[j][0], history.at(j)[1]);
        j++;
    } 
}

我代码中的例程在哪里:

void populateArray(int input, int time) {
    values.push_back(time);
    values.push_back(input);
    if (history.size() > 0) {
        values.push_back(values[0] - history.back()[0]);
        values.push_back(values[1] - history.back()[1]);
        values.push_back(values[3] / values[2]);
    }
    history.push_back(values);
    values.clear();
};

"超出范围"错误源于history.size()2populateArray调用中的两个push_back);但在你的测试中,你检查了history[i]i110

while (i < 10) {
    i++;
    Assert::AreEqual(history[i][4], graph[2][i]);
}

在单元测试中,没有任何东西应该被认为是100%确定的,更喜欢std::vecor::at(size_type pos)而不是std::vector::operator[](size_type pos);更多信息,这个好答案来自另一个SO问题。

此外,请考虑Bo·佩尔森的评论。