写到这里,我们发现了两个问题,首先我们不停的初始化一些测试所需的对象,重复了很多代码;其次我们发现了一个接口设计错误,我们的接口设计上没有考虑一个文件不存在的情况。从中可见,先写好测试用例,不仅是对实现的测试,也是对我们设计的测试。TestFixture定义了两个成员函数setUp和tearDown,在每一个测试用例被执行的时候,和它定义在同一个类内部的setUp和tearDown会被调用以进行初始化和清除工作。我们可以用这两个函数来进行统一的初始化代码。并且,我们修改 getFileSize、setFileModifyDate和getFileModifyDate使得它们在出现错误的时候,抛出异常 FileStatusError。下面是我们的测试用例:
class MyTestCase:public CPPUNIT_NS::TestFixture
{
std::string mFileNameExist;
std::string mFileNameNotExist;
std::string mTestFolder;
enum DUMMY
{
FILE_SIZE = 1011
};
public:
virtual void setUp()
{
mTestFolder = "c:justfortest";
mFileNameExist = mTestFolder + "exist.dat";
mFileNameNotExist = mTestFolder + "notexist.dat";
if( GetFileAttributes( mTestFolder.c_str() ) != INVALID_FILE_ATTRIBUTES )
throw std::exception( "test folder already exists" );
if( ! CreateDirectory( mTestFolder.c_str() ,NULL ) )
throw std::exception( "cannot create folder" );
HANDLE file = CreateFile( mFileNameExist.c_str(), GENERIC_READ | GENERIC_WRITE,
0, NULL, CREATE_NEW, 0, NULL );
if( file == INVALID_HANDLE_VALUE )
throw std::exception( "cannot create file" );
char buffer[FILE_SIZE];
DWORD bytesWritten;
if( !WriteFile( file, buffer, FILE_SIZE, &bytesWritten, NULL ) ||
bytesWritten != FILE_SIZE )
{
CloseHandle( file );
throw std::exception( "cannot write file" );
}
CloseHandle( file );
}
virtual void tearDown()
{
if( ! DeleteFile( mFileNameExist.c_str() ) )
throw std::exception( "cannot delete file" );
if( ! RemoveDirectory( mTestFolder.c_str() ) )
throw std::exception( "cannot remove folder" );
}
void testCtorAndGetName()
{
FileStatus status( mFileNameExist );
CPPUNIT_ASSERT_EQUAL( status.getFileName(), mFileNameExist );
}
void testGetFileSize()
{
FileStatus exist( mFileNameExist );
//这里FILE_SIZE缺省是int,而getFileSize返回DWORD,不加转换会导致模版不能正确匹配。
CPPUNIT_ASSERT_EQUAL( exist.getFileSize(), (DWORD)FILE_SIZE );
FileStatus notExist( mFileNameNotExist );
CPPUNIT_ASSERT_THROW( notExist.getFileSize(), FileStatusError );
}
void testFileExist()
{
FileStatus exist( mFileNameExist );
CPPUNIT_ASSERT( exist.fileExist() );
FileStatus notExist( mFileNameNotExist );
CPPUNIT_ASSERT( ! notExist.fileExist() );
}
void testFileModifyDateBasic()
{
FILETIME fileTime;
GetSystemTimeAsFileTime( &fileTime );
FileStatus exist( mFileNameExist );
CPPUNIT_ASSERT_NO_THROW( exist.getFileModifyDate() );
CPPUNIT_ASSERT_NO_THROW( exist.setFileModifyDate( &fileTime ) );
FileStatus notExist( mFileNameNotExist );
CPPUNIT_ASSERT_THROW( notExist.getFileModifyDate(), FileStatusError );
CPPUNIT_ASSERT_THROW( notExist.setFileModifyDate( &fileTime ), FileStatusError );
}
void testFileModifyDateEqual()
{
FILETIME fileTime;
GetSystemTimeAsFileTime( &fileTime );
FileStatus exist( mFileNameExist );
CPPUNIT_ASSERT_NO_THROW( exist.setFileModifyDate( &fileTime ) );
FILETIME get = exist.getFileModifyDate();
// 这里 FILETIME 没有定义 operator==,所以不能直接使用 CPPUNIT_ASSERT_EQUAL
CPPUNIT_ASSERT( CompareFileTime( &get, &fileTime ) == 0 );
}
};
文章来源于领测软件测试网 https://www.ltesting.net/