[英]Unit Testing Mathematical C++ routine
测试数学例程的最佳实践是什么? 我正在使用下面的例程,并尝试为其编写单元测试(我只是在学习单元测试)。 我正在使用内置的Visual Studio框架。
每当我开始尝试使用Assert
命令针对已知的正确答案检查实际值时,我最终都会编写要测试的相同代码来进行比较,这显然并不能证明任何事情。 常规的处理方式是什么?
int averageGradient(int x1, int x2, float m) {
int i = 0, y1 = 0, y2 = 0;
while (y1 != 0 && y2 != 0) { //if both y values haven't been solved then keep trying
if (x1 >= graph[0][i] && x1 < graph[1][i] && y1 == 0) { // if x1 lies in the first straight line segment
y1 = (graph[2][i] * x1) + graph[3][i]; // then calculate it's y value (y1)
}
else { i++; } //otherwise incriment i to check the next straight line segment
if (x2 >= graph[0][i] && x2 < graph[1][i]) { //try the same thing for x2
y2 = (graph[2][i] * x2) + graph[3][i]; //calculate its y value (y2)
}
else { i++; }
}
m = (y2 - y1) / (x2 - x1);
return m;
};
您预先计算了预期的结果(可能是数学应用程序或表格数据),然后将该“硬编码”值放入Assert中:
AssertEqual(calculatePiFirst6Decimals(), 3.141519);
方法是测试已知的值/结果(否则就没有一点可以测试的东西,无法验证)。 然后,也应该测试已知的边缘情况(例如,当参数取极值或需要特别注意时)
我不明白
var a = knownParameter1;
var b = knownParameter2;
var c = knownParameter3;
var ret = knownReturnValue;
Assert(ret == averageGradient(a, b, c));
您不会再写相同的代码了...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.