我以前并不太习惯编写单元测试,现在我开始意识到这个重要性了,并且需要检查自己是否正确的做法。
假设你有一个处理数学运算的类。
class Vector3
{
public: // Yes, public.
float x,y,z ;
// ... ctors ...
} ;
Vector3 operator+( const Vector3& a, const Vector3 &b )
{
return Vector3( a.x + b.y /* oops!! hence the need for unit testing.. */,
a.y + b.y,
a.z + b.z ) ;
}
我想到了两种测试Vector类的方法:
1) 先手动解决一些问题,然后将答案硬编码到单元测试中,只有当答案与手动硬编码的结果相等时才通过测试
bool UnitTest_ClassVector3_operatorPlus()
{
Vector3 a( 2, 3, 4 ) ;
Vector3 b( 5, 6, 7 ) ;
Vector3 result = a + b ;
// "expected" is computed outside of computer, and
// hard coded here. For more complicated operations like
// arbitrary axis rotation this takes a bit of paperwork,
// but only the final result will ever be entered here.
Vector3 expected( 7, 9, 11 ) ;
if( result.isNear( expected ) )
return PASS ;
else
return FAIL ;
}
2) 仔细重写单元测试中的计算代码。
bool UnitTest_ClassVector3_operatorPlus()
{
Vector3 a( 2, 3, 4 ) ;
Vector3 b( 5, 6, 7 ) ;
Vector3 result = a + b ;
// "expected" is computed HERE. This
// means all you've done is coded the
// same thing twice, hopefully not having
// repeated the same mistake again
Vector3 expected( 2 + 5, 6 + 3, 4 + 7 ) ;
if( result.isNear( expected ) )
return PASS ;
else
return FAIL ;
}
还有其他的方法可以做类似这样的事情吗?