Tuesday, September 05, 2006

Cases of unit test

Case 1:
1. Subject: Design a method 'filterStringList' to erase those strings whose length is not less than 4 out from a list. The prototype of the method is declared like this:
typedef list StringList;
typedef unsigned int StringLength;
void filterStringList(StringList &list, const StringLength maxLength);
2. Unit test design:
void test_filterStringList()
{
StringList strList;
strList.push_back("1");
strList.push_back("22");
strList.push_back("333");
strList.push_back("4444");
strList.push_back("55555");
strList.push_back("666666");

filterString(strList, 4);
CPPUNIT_ASSERT(3 == strList.count());
CPPUNIT_ASSERT("1" == strList.[0]);
CPPUNIT_ASSERT("22" == strList.[1]);
CPPUNIT_ASSERT("33" == strList.[2]);
}

3. My first impletement (fail to run unit test)
void filterStringList(StringList &list, const StringLength maxLength)
{
StringList::iterator it = list.begin();
for(; it != list.end(); ++i)
{
if((*it).length() >= maxLength)
it = list.erase(it);
}
}

It can't passed the test.

4. The final impletement

void filterStringList(StringList &list, const StringLength maxLength)
{
StringList::iterator it = list.begin();
while(it != list.end())
{
if((*it).length() >= maxLength)
it = list.erase(it);
else
++it;
}
}

No comments: