→ dos792:testing object-oriented system, by binder 08/04 22:09
目前自學unit testing,用的是google testing framework
自己寫一個表示有理數class (CRational),然後測試該class
欲測試的有理數class如下:
class CRational
{
public:
CRational(int nNum, int nDen);
CRational(const CRational& rhs);
CRational& operator=(const CRational& rhs);
const CRational operator*(const CRational& rhs) const;
const CRational operator+(const CRational& rhs) const;
const CRational operator-(const CRational& rhs) const;
const CRational operator/(const CRational& rhs) const;
const bool operator==(const CRational& rhs);
const bool operator!=(const CRational& rhs);
const bool operator< (const CRational& rhs);
const bool operator<=(const CRational& rhs);
const bool operator> (const CRational& rhs);
const bool operator>=(const CRational& rhs);
//Simplify the rational number to its smallest form
void Simplify();
bool IsValid() const;
int GetNumerator() const;
int GetDenominator() const;
private:
//Find Greatest Common Divisor
int GetGcd() const;
private:
int m_nNumerator;
int m_nDenominator;
};
測試該class的程式碼片段如下:
TEST(RationalTest, PositiveValue)
{
CRational r(1, 2);
EXPECT_EQ(1, r.GetNumerator());
EXPECT_EQ(2, r.GetDenominator());
EXPECT_EQ(true, r.IsValid());
CRational r2(5, 3);
EXPECT_EQ(5, r2.GetNumerator());
EXPECT_EQ(3, r2.GetDenominator());
EXPECT_EQ(true, r2.IsValid());
CRational r3(0, 5);
EXPECT_EQ(0, r3.GetNumerator());
EXPECT_EQ(5, r3.GetDenominator());
EXPECT_EQ(true, r3.IsValid());
}
TEST(RationalTest, Addition)
{
CRational r1(1, 7);
CRational r2(2, 7);
CRational r3 = r1 + r2;
EXPECT_EQ(3, r3.GetNumerator());
EXPECT_EQ(7, r3.GetDenominator());
CRational r4(1, 6);
CRational r5(2, 6);
CRational r6 = r4 + r5;
EXPECT_EQ(1, r6.GetNumerator());
EXPECT_EQ(2, r6.GetDenominator());
CRational r7(-1, 5);
CRational r8(2, 5);
CRational r9 = r7 + r8;
EXPECT_EQ(1, r9.GetNumerator());
EXPECT_EQ(5, r9.GetDenominator());
//...
}
目前遭遇到幾個問題
1. 每個Test Case中都會創建出很多CRational的instance (r1, r2, r3, r4, ...)
有很多duplicated code,要怎麼樣才能把testing code寫的簡潔一點??
進而消除這些duplicated code
2. 要怎麼才能測試到CRational的private method (本例中的GetGcd())??
thanks in advance
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 111.240.135.190