cppcheck是一种C/C++静态代码检测工具。提供了命令行和图形界面(QT),源码很值得一读,代码中定义基类TestFixture,该类继承自ErrorLogger,实际是对检测结果做了统一的判断和定义。定义了各种各样的断言和标准输出重定向等。代码本身是对模板模式(或许还用到了单列模式)的最好说明,我们将单元测试n源代码实现框架抽取出来可以得到:
#include <iostream>
#include <list>
using namespace std;
#define REGISTER_TEST( CLASSNAME ) namespace { CLASSNAME m_##CLASSNAME; }
class TestFixture;
/**
* TestRegistry
**/
class TestRegistry
{
private:
std::list<TestFixture *> _tests;
public:
static TestRegistry &theInstance()
{
static TestRegistry testreg;
return testreg;
}
void addTest(TestFixture *t)
{
_tests.push_back(t);
}
const std::list<TestFixture *> &tests() const
{
return _tests;
}
};
class TestFixture
{
public:
TestFixture(const std::string &_name)
{
this->m_name = _name;
TestRegistry::theInstance().addTest(this);
}
static void runTests(void)
{
const std::list<TestFixture *> &tests = TestRegistry::theInstance().tests();
for (std::list<TestFixture *>::const_iterator it = tests.begin(); it != tests.end(); ++it)
{
(*it)->processOptions();
(*it)->run();
}
}
protected:
virtual void run() = 0;
void processOptions(void)
{
cout << "processOptions:" << m_name << endl;
}
private:
string m_name;
};
class TestBoost : public TestFixture {
public:
TestBoost() : TestFixture("TestBoost")
{ }
private:
void run() {
cout << "run:TestBoost class " << endl;
}
};
class TestOther : public TestFixture {
public:
TestOther() : TestFixture("TestOther")
{ }
private:
void run() {
cout << "run:TestOther class " << endl;
}
};
REGISTER_TEST(TestBoost)
REGISTER_TEST(TestOther)
int main(int argc, char *argv[])
{
TestFixture::runTests();
return 0;
}主函数中运行基类的静态函数runTests。如果需要扩展的话,只需要继承自TestFixture类即可。REGISTER_TEST的作用是全局App,这个跟MFC有些类似。全局App初始化过程中会调用基类的构造函数,而基类TestFixture构造函数中直接将子类对象指针保存到了一个静态LIST对象列表中(注意,派生类和基类this指针值是一样的,因为派生对象内存模型是继承自基类对象的内存模型,对象首地址一样)。我们把runTests可看做模板,即由基类规定打印顺序和指定规则,而将某些步骤具体实现延迟到子类。这样就可以实现单元测试类扩展了,比如扩展再扩展一个类TestApp,则只需要做下面2步,第一:将TestApp继承自TestFixture,实现run虚接口,最后注册REGISTER_TEST(TestApp),就可以了。上面代码运行结果如下:
cppcheck是一款用于C/C++的静态代码检测工具,具备命令行和QT图形界面。其内部利用模板模式设计,如TestFixture基类,继承自ErrorLogger。通过定义各种断言和输出重定向,提供了一个单元测试框架。开发者可通过继承TestFixture并注册测试,实现测试类的扩展。在主函数中,通过runTests静态方法执行测试,而构造函数中保存子类对象至静态列表,实现按特定顺序运行。这种方式允许灵活地添加新的测试类。

515

被折叠的 条评论
为什么被折叠?



