How do I compile and link unit tests?

I recently started using TDD in one of my C ++ projects. I am very new to this and I have some very basic questions regarding how unit tests are compiled and used. I am using Boost.Test library on Linux.

  • Is it common to compile one large test program containing all test suites for all of your departments? How about splitting your tests into several small, independent test programs?

  • How are processing (s make

    ) linked ? Each test program object must be linked to an object file (s) from my original program, which contains everything that will be tested. Is there a way to handle this automatically? To be more specific, is there anyway to write Makefile

    to make

    automatically detect which object files need to be linked together in order to generate a specific unit test program?

Update . My code is organized in many .cpp / .h files and is currently monolithic (no libraries). Unit tests are in a separate directory, usually in a 1 to 1 ratio with the .cpp files from my source tree.

Update 2 . Hoping this will make my question less broad, here is an excerpt from the Makefile I'm using:

$(TSTDIR)%.$(TEST): $(OBJDIR)%.$(TEST).$(OBJEXT) $(OBJDIR)%.$(OBJEXT)
    @mkdir -p $(@D)
    @$(CXX) -o $@ $^ $(TSTLIBS)

$(OBJDIR)%.$(OBJEXT): $(SRCDIR)%.$(SRCEXT) $(DEPDIR)%.$(DEPEXT)
    @mkdir -p $(@D)
    @$(CXX) $(CXXFLAGS) $(INCLUDES) -o $@ $<

      

$(TEST)

is just a marker that I use to distinguish between my unit tests and other files. Note that I am currently linking all test programs to an object file of the same name. However, this will break if symbols from another object file are also needed.

Update 3 . This is an example of what I am talking about in the previous paragraph.

MyOtherClass.h:

class MyOtherClass
{
public:
    int Foo();
}

      

MyOtherClass.cpp:

#include "MyOtherClass.h"

int MyOtherClass::Foo()
{
    return 0;
}

      

MyClass.h:

#include "MyOtherClass.h"

class MyClass
{
public:
    int Foo();

private:
    MyOtherClass moc_;
}

      

MyClass.cpp:

#include "MyClass.h"

int MyClass::Foo()
{
    return moc_.Foo();
}

      

TestMyClass.cpp will check if it returns MyClass::Foo

0. Using my current Makefile this will not compile since the test program must be linked to both MyClass.o and MyOtherClass.o.

+3


source to share


1 answer


I found this great answer that was asked by a related question.



You can solve the linking problem with static or dynamic libraries. If the object files under test are compiled into libraries, then when you link the unit test program, it pulls any required dependencies from the library.

+1


source







All Articles