Qt: How to organize Unit Test with more than one class?

后端 未结 6 1542
温柔的废话
温柔的废话 2020-12-29 03:10

I have a Qt Unit test (sub)project, which generates me one class (with the main generated by QTEST_APPLESS_MAIN).I can start this from within Qt Creator as cons

6条回答
  •  星月不相逢
    2020-12-29 03:31

    Searching for this same answer, I found a very good solution from http://qtcreator.blogspot.de/2009/10/running-multiple-unit-tests.html. He creates a namespace with a container that registers all the tests created (via the DECLARE_TEST macro), and then uses it to run all the tests on the list. I rewrote it to fit my code and I post my version here (My Qt Creator version: 4.1.0):

    /* BASED ON
     * http://qtcreator.blogspot.de/2009/10/running-multiple-unit-tests.html
     */    
    #ifndef TESTCOLLECTOR_H
    #define TESTCOLLECTOR_H
    
    #include 
    #include 
    #include 
    #include 
    
    namespace TestCollector{
    typedef std::map > TestList;
    inline TestList& GetTestList()
    {
       static TestList list;
       return list;
    }
    
    inline int RunAllTests(int argc, char **argv) {
        int result = 0;
        for (const auto&i:GetTestList()) {
            result += QTest::qExec(i.second.get(), argc, argv);
        }
        return result;
    }
    
    template 
    class UnitTestClass {
    public:
        UnitTestClass(const std::string& pTestName) {
            auto& testList = TestCollector::GetTestList();
            if (0==testList.count(pTestName)) {
                testList.insert(std::make_pair(pTestName, std::make_shared()));
            }
        }
    };
    }
    
    #define ADD_TEST(className) static TestCollector::UnitTestClass \
        test(#className);
    
    #endif // TESTCOLLECTOR_H
    

    Then, just add the ADD_TEST(class) line in your test header like this:

    #ifndef TESTRANDOMENGINES_H
    #define TESTRANDOMENGINES_H
    
    #include 
    #include "TestCollector.h"
    
    class TestRandomEngines : public QObject
    {
        Q_OBJECT
    
    private Q_SLOTS:
        void test1();
    };
    
    ADD_TEST(TestRandomEngines)
    
    #endif // TESTRANDOMENGINES_H
    

    And and to run all the tests, just do:

    #include "TestCollector.h"
    #include 
    
    int main(int argc, char *argv[]) {
        auto nFailedTests = TestCollector::RunAllTests(argc, argv);
        std::cout << "Total number of failed tests: "
                  << nFailedTests << std::endl;
        return nFailedTests;
    }
    

提交回复
热议问题