长函数的测试
上一篇 /
下一篇 2012-07-05 09:47:48
/ 个人分类:单元测试
在单元测试过程中,有一种函数比较长,一般来说,它违背了单一职责的原则。该函数功能较多,应该可以细化拆分成若干小功能的函数。从单元测试的角度来看,在测试该函数时,需要构造很多数据,且这些数据仅是为了函数正常运行,对测试点没有任何帮助。因此基于上述原因,必然导致此函数的分支覆盖困难。
例如下面这段代码,测试起来就很困难:
floatGetScore(){ //compute first
score float first_score
= 0; for(Pi in P1…P4){ first_score += //省略部分代码 } //compute second
score float second _score
= 0; for(Pi in P1…P4){ second_ second +=
//省略部分代码 } //compute third
score float third _score
= 0; for(…){ third _score += //省略部分代码 } //compute weight float result =
0.1* first _score + 0.2* second _score + 0.3* third _score ; return result; } |
测试代码要尝试测试系数权重是否正确:
FIRST() { //构造first/second/ third /teach score //并且要保证它们能够正确运行 EXPECT_TRUE(3.14
== GetScore()); //如果某一个score的计算方式改变,需要修改整个case } |
拆分后的函数:
floatGetScore()
{ float first_score
=GetFirstScore(); float second_score
=GetSecondScore(); float third_score
=GetThirdScore(); returnComputeWeight(first_score,
second_score, third_score); } floatGetFirstScore()
{ //省略部分代码 } floatGetSecondScore()
{ //省略部分代码 } floatGetThirdScore()
{ //省略部分代码 } floatComputeWeight(float
first_score, float second_score,
float third_score,) { return 0.1* first_score
+ 0.2* second_score + 0.3* third_score; } |
这样测试权重就变简单了:
TEST(){ //直接构造first/second/third的value即可 EXPECT_TRUE(1.4 ==ComputeWeight(1, 2, 3)); //不依赖于GetTestScore的策略,它们改变,该case不用修改 } |
合理的将大函数迚行拆分,是一个比较好的手段,当然如何拆分细化是合理的,还需要根据具体情况而定,满足高内聚,低耦合一般来说都是OK的。
收藏
举报
TAG: