unit-testing - 编写单元测试的好方法

标签 unit-testing

所以,我以前并没有真正在编写单元测试的实践中——现在我有点,我需要检查我是否在正确的轨道上。

假设您有一个处理数学计算的类(class)。

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

或者还有其他方法可以做这样的事情吗?

最佳答案

方式 #1 是进行单元测试的普遍接受的方式。通过重写代码,您可能会将错误代码重写到测试中。很多时候,您测试的每个方法只需要一个真实的测试用例,因此不会太耗时。

关于unit-testing - 编写单元测试的好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3033099/

相关文章:

java - Apache Camel 单元测试用例

C#:带有用于单元测试的静态类的 DI

c# - 如何在 C# 中创建用于测试目的的模拟任务对象?

unit-testing - 使用 Webpack、Jasmine (-core)、typescript 进行单元测试

ios - iOS 中的单元测试完成 block

c++ - QT UI 测试的最佳方法

java - 无法在 Spring 3.2.8 和 junit 4.4 中 Autowiring 现场执行 Junit 测试

asp.net-mvc - 流畅的安全单元测试

java - 如何对 HTTPServlet 进行单元测试?

javascript - 如何在 AngularJS 中测试 Service 与 IndexedDB 的配合