我正在对一个例程进行单元测试,该例程应从 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/