0

I am trying to add some unit tests to my existing projecting. I am probably writing unit tests for the first time, so my knowledge is limited.

  • Do I need to include all the header files of the project file into test file as well?

e.g if My file Addition.cpp has an include "Calculate.h" and I want to test any function Additiion.cpp. Do i need add Calculate and Addition header file

Henrique Jung
  • 1,408
  • 1
  • 15
  • 23

1 Answers1

0

Most likely you don't.

I spent some time considering your question and I think I've never seen any special rule regarding include headers and unit tests. However, based on my experience I think we can start with the following:

Include only the header you want to unit test and consider it carefully before adding a second one.

What does that means? Well let's assume you want to test your Addition.h API and then you craft the following on your Test.cpp

#include "gtest/gtest.h"

#include "Addition.h"

TEST(AdditionTest, TwoPlusTwo) {
  EXPECT_EQ(4, Add(2, 2));
}

You hit compile and then got this message:

In file included from 
Test.cpp:3:
Addition.h:4:1: error: unknown type name 'result_t'
result_t Add(int a, int b)
^
1 error generated.

Congratulations! Your unit test found a bug! Apparently your Addition.h header is not self-contained, since it's trying to use a type - result_t - that the compiler does not know yet. You fix that by adding the header file that implement the type result_t to Addition.h, not Test.cpp.

Of course some times it's valid to add a new header to the include files of the test itself. Imagine that Addition.h receives an argument that is result_t*, and result_t is now an opaque type known only to the internal implementation in Addition.cpp. In this case, your unit might need to know a little more about result_t than Addition.h, which makes it valid to add an extra include to Test.cpp.

In short, in the simplest case, you add only the header you want to directly test and analyse every error with care because they just might be your first bugs.

Henrique Jung
  • 1,408
  • 1
  • 15
  • 23