本文主要是介绍cppcheck 单元测试框架浅析,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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 单元测试框架浅析的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!