## 编写单元测试的好方法内容来源于 Stack Overflow，并遵循CC BY-SA 3.0许可协议进行翻译与使用

• 回答 (2)
• 关注 (0)
• 查看 (20)

```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 ) ;
}```

## 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 ;
}```

### 2 个回答

```expected.x == 7;
expected.y == 9;
expected.z == 11;```