c++ - 使用 vector 操作的单元测试中未处理的 C++ 异常

标签 c++ unit-testing vector

我正在对一个例程进行单元测试,该例程应从 vector 中获取一些数据,对其进行处理并将其放回 vector 的 vector 中。但是,它从我的 Visual Studio 2015 单元测试中抛出未处理的 C++ 异常(下面的完整错误描述),我的代码有什么问题?

此测试方法抛出错误:

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

Result StackTrace: at std::vector >,std::allocator > > >::_Xran() in c:\program files (x86)\microsoft visual studio 14.0\vc\include\vector:line 1789 at std::vector >,std::allocator > > >::at() in c:\program files (x86)\microsoft visual studio 14.0\vc\include\vector:line 1208 at UnitTest1::MyTests::Graph_Equations_Correct() in c:\users\george\documents\history testing 2\unittest1\unittest1.cpp:line 32 Result Message: Unhandled C++ Exception

这里是 DrawGraph():

vector< vector<float> > graph;
void drawGraph() {
    float m, c, j, x1, x2;
    vector<float> values;
    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++;
        values.push_back(x1);
        values.push_back(x2);
        values.push_back(m);
        values.push_back(c);
        graph.push_back(values);
        values.clear();
    }
};

历史是另一个载体。在第一行它只有两个值,但随后的每一行(其中 14 个以上)都有 5 个值,因此是 15 x 5,顶行只有 2 个值。我已经调试过了,这是正确的。此外,从 Assert 行替换图形引用可消除错误,因此我认为这就是问题所在。

最佳答案

根据您发布的内容,问题是您有两个不同的 graph vector ,一个本地 vector 和一个全局 vector 。

您正在 drawGraph 函数中填充全局图形,但在测试函数中访问本地的、未填充的图形。

如果您使用 vector::at() 而不是 operator[] 来访问测试函数中的元素,而不是未处理的异常,out_of_range 异常将被抛出,从而更清楚地指出问题。

关于c++ - 使用 vector 操作的单元测试中未处理的 C++ 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34295344/

相关文章:

c# - Moq It.Is<> 不匹配

R将向量 reshape 为多列

c++ - 试图读取充满对象的 vector 的访问冲突

c++ - 模板类自动类型转换的运算符重载

c++ - 带有反向迭代器的 std::vector 上的 std::lower_bound 产生错误的结果

c++ - 如何在创建实例时将实例本身传递给外部 map ?

c++ - 如何用结构化的等价物替换 continue 和 goto 语句?

c++ - 嵌套命名空间如何工作?

ios - 如何在 xcode 4.5 上从命令行运行 IOS 单元测试

reactjs - 如何测试无状态组件