首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >编写单元测试的好方法

编写单元测试的好方法
EN

Stack Overflow用户
提问于 2010-06-14 01:01:10
回答 6查看 2.7K关注 0票数 18

因此,我以前并不是真正地在实践中编写单元测试-现在我在某种程度上,我需要检查我是否在正确的轨道上。

假设你有一个处理数学计算的类。

代码语言:javascript
复制
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)手工解决一些问题,然后将数字硬编码到单元测试中,只有在与手工和硬编码结果相等的情况下才能通过

代码语言:javascript
复制
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)在单元测试中非常小心地重写计算代码。

代码语言:javascript
复制
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 ;
}

或者,有没有其他方法来做这样的事情?

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3033099

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档