English Spanish Български

Unit testing with QTest

For a basic overview how to write unit tests with qtestlib, you should refer to the official manual. [qt-project.org]

Test Output

Output to a txt file

  1. QStringList testCmd;
  2. QDir testLogDir;
  3. testLogDir.mkdir("UnitTest_Results");
  4. testCmd<<" "<<"-o" <<"UnitTest_Results/test_log.txt";
  5. QTest::qExec(myTestClass,testCmd);

Output in xml format:

  1. QStringList testCmd;
  2. QDir testLogDir;
  3. testLogDir.mkdir("UnitTest_Results");
  4. testCmd<<" "<<"-xml" <<"-o" <<"UnitTest_Results/test_log.xml";
  5. QTest::qExec(myTestClass,testCmd);

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.

  1. enable_testing(true)
  2. include_directories( test )
  3.  
  4. set(test_additional
  5.     some_dependency.cpp
  6.     some_other_dependency.cpp
  7. )
  8. add_test(dummytest test/DummyTest.cpp)

If you do not want to have tests built all the time, remove

  1. enable_testing()
and run cmake with
  1. cmake .. -DENABLE_TESTING=true
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

  1. add_test()
to ctest test “database”.

  1. MACRO(add_test testname testsrc)
  2.     SET(test_${testname}_SRCS ${testsrc})
  3.  
  4.     qt4_automoc(${test_${testname}_SRCS})
  5.     add_executable(test_${testname} ${test_${testname}_SRCS} ${test_additional})
  6.     target_link_libraries(test_${testname} ${QT_QTCORE_LIBRARY}
  7.             ${QT_QTTEST_LIBRARY} ${QT_QTGUI_LIBRARY}
  8.             ${GSOAP_LIBRARIES} ${QT_QTLOCATION_LIBRARY})
  9.  
  10.     ADD_TEST(test_${testname} test_${testname})
  11. ENDMACRO(add_test)

Tests can be compiled with

  1. make
and run either directly by name of the test (test_${testname} as specified in the macro) or every test as batch with
  1. make test

Categories: