QtTest Unit Testing, how to add header files located in another project?

7.1k views Asked by At

Maybe I'm missing something, but it seems really stupid to me that the only tutorial provided for QtTest framework has you testing the QString class.

The typical use case for unit testing is....testing classes you wrote yourself, but there is no mention on how to reference your classes in a different project for testing in the tutorial and google has failed me as well(and I really doubt copy pasting classes is a good way to do it).

I even thumbed through 3 different Qt books with no mention of QtTest.

2

There are 2 answers

1
AJG85 On BEST ANSWER

You can add include paths to other project directories in your .pro file like so:

INCLUDEPATH += <directory>

Then it should be able to find the headers that you are including.

Edit: Based on comment

That's another story altogether. Undefined reference usually means you are missing a dependency. This can usually be resolved with one of two things.

The simplest is to include the missing source file:

INCLUDEPATH += ../myotherproject/
SOURCES = main.cpp ../myotherproject/missingsource.cpp

Perhaps the better solution is to expose reusable code by compiling it as a library and linking to it. E.g. a .DLL or .LIB on Windows and .SO or .A on Linux.

INCLUDEPATH += ../myotherproject/
win32:LIBS += ../myotherproject/linkme.lib

Can you show us the specific errors you are getting?

1
leemes On

I suggest that you put all sources and headers which both your main application project and your unit test project need into one .pri (.pro include) file. Put this file in the main project. Then include this file in both projects.

Note that whenever adding a new class to the main project, QtCreator automatically appends the SOURCES += and HEADERS += lines to the .pro file, but you want them to be in the .pri file, so you need to move them afterwards manually. I think that there is no solution to tell QtCreator where to put them.


Main project:

myproject.pro
myproject.pri
main.cpp
someclass.h
someclass.cpp

myproject.pro:

QT += ...
TARGET = ...
...

SOURCES += main.cpp       # "private" to this project
include(myproject.pri)    # needed in unit test

myproject.pri:

SOURCES += someclass.cpp
HEADERS += someclass.h

Unit test project:

unittest.pro
main.cpp
test.h
test.cpp

unittest.pro:

QT += ...
TARGET = ...
...

SOURCES += main.cpp test.cpp
HEADERS += test.h

# include the classes from the main project:
INCLUDEPATH += ../myproject/
include(../myproject/myproject.pri)