Unit Testing
Unit testing with QTest
For a basic overview how to write unit tests with qtestlib, you should refer to the "official manual.":http://doc.qt.io/qt-5.0/qttestlib/qtest-tutorial.html
Test Output
Output to a txt file
QStringList testCmd;<br />QDir testLogDir;<br />testLogDir.mkdir("UnitTest_Results&quot;);<br />testCmd&lt;<" "<<"-o&quot; <<"UnitTest_Results/test_log.txt&quot;;<br />QTest::qExec&amp;#40;myTestClass,testCmd&amp;#41;;
Output in xml format:
QStringList testCmd;<br />QDir testLogDir;<br />testLogDir.mkdir("UnitTest_Results&quot;);<br />testCmd&lt;<" "<<"-xml&quot; <<"-o&quot; <<"UnitTest_Results/test_log.xml&quot;;<br />QTest::qExec&amp;#40;myTestClass,testCmd&amp;#41;;
The above code will run the test and the output will be generated in xml format. The xml file can be parsed and the details can be displayed in an appropriate way as per the requirements.
Running and compiling QTests with CTest
CTest, by design, is only a facility for testing. For that it scales to very different unit tests frameworks, and works out of box with QTest.
The snippet below goes to CMakeLists.txt, and specifies files that are used for the test.
<br />enable_testing(true)<br />include_directories( test )
set(test_additional<br /> some_dependency.cpp<br /> some_other_dependency.cpp<br />)<br />add_test(dummytest test/DummyTest.cpp)<br />
If you do not want to have tests built all the time, remove
enable_testing()<code> and run cmake with <code>cmake .. -DENABLE_TESTING=true<code> in order to build tests.
The macro below uses variable ${test_additional} to give additional source files for test to compile, the files that are needed for test. It adds the test with
add_test() to ctest test “database”.
<br />MACRO (add_test testname testsrc)<br /> SET (test_$&#123;testname&#125;_SRCS $&#123;testsrc&#125;)
qt4_automoc(${test_${testname}_SRCS})<br /> add_executable(test_${testname} ${test_${testname}_SRCS} ${test_additional})<br /> target_link_libraries(test_${testname} ${QT_QTCORE_LIBRARY}<br /> ${QT_QTTEST_LIBRARY} ${QT_QTGUI_LIBRARY}<br /> ${GSOAP_LIBRARIES} ${QT_QTLOCATION_LIBRARY})
ADD_TEST(test_${testname} test_${testname})<br />ENDMACRO (add_test)<br />
Tests can be compiled with make
and run either directly by name of the test (test_${testname} as specified in the macro) or every test as batch with
make test