因此,我以前并不是真正地在实践中编写单元测试-现在我在某种程度上,我需要检查我是否在正确的轨道上。
假设你有一个处理数学计算的类。
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 ;
}
或者,有没有其他方法来做这样的事情?
https://stackoverflow.com/questions/3033099
复制相似问题