ComplexNumberTest( std::string name ) : CppUnit::TestCase( name ) {}
void runTest() {
CPPUNIT_ASSERT( MyComplex (10, 1) == MyComplex (10, 1) ); // note:1
CPPUNIT_ASSERT( !(MyComplex (1, 1) == MyComplex (2, 2)) ); //note:2
}
};
这个测试用例的意图很明显,就是对MyComplex类进行相等测试,根据复数的数学知识,能够得到note:1处我们期望的是相等,而note:2处则是不等。有了这个测试用例后,对其进行编译,由于MyComplex类没有进行定义,因此将无法通过编译,不过,这是单元测试中必然会遇到的问题。对于无法编译的恐惧驱使我们尽快的完成下面的代码:
//If we compile now ,we get compile error.So keep fixing it.
bool operator==( const MyComplex &a, const MyComplex &b)
{
return true;
}
//Now compile it again,Ok!Run it,we'll get some fail.
//This is because the operator==() doesn't work properly.Keep fixing it.
现在编译没问题了,可以松一口气了,不过无法通过测试,于是再接再厉,写下:
class MyComplex {
friend bool operator ==(const MyComplex& a, const MyComplex& b);
double real, imaginary;
public:
MyComplex( double r, double i = 0 )
: real(r)
, imaginary(i)
{
}
};
bool operator ==( const MyComplex &a, const MyComplex &b )
{
return a.real == b.real && a.imaginary == b.imaginary;
}
//If we compile now and run our test it will pass.
编译,测试,通过了,这个世界清静了,恍如来到了桃花源…
不过,我们要的尽善尽美,MyComplex不够美丽,于是改了个名字CComplex,这下大功告成,但是,心里始终还是有个结,如何把它用在自己的项目中呢?欲知后事,请代下回分解。
文章来源于领测软件测试网 https://www.ltesting.net/