Home > Software engineering >  How to do Google test for function which are not a part of class?
How to do Google test for function which are not a part of class?

Time:07-06

Am performing Google test, Here am facing one challenge.

In my project some of the functions are not included in the header file, they are directly included in the source file. I can access the functions which are in header file by creating obj of the class but am not able to access which are only in source file.

Please guide me how to access these function.

Thanks in advance!. Kiran JP

CodePudding user response:

Declare them extern in your test code.

Example. Let's say you have a source file like this:

// Function declared and defined in .cpp file
void myFunction() {
    // implementation
}

Then you could go ahead and do the following in your test code:

extern void myFunction();

TEST(MyTest) {
    myFunction();
}

Unless the function was explicitly declared with internal linkage. Either by declaring it static or by declaring/defining it inside an anonymous namespace in C 11 or above.

CodePudding user response:

You will need to add the declaration of those functions to a header file, either to your existing header files, or to a new header file.

For example, say you have this function in your class.cc file without any declaration in class.h file:

int SomeFunction(int a, int b){
  //...
}

You should add the following line to a header file. Let's call it header.h:

// header.h
int SomeFunction(int a, int b);

Then modify your test file to include header.h:

#include "header.h"

TEST(SomeFunction, Test1) {
    int c = SomeFunction(1,2);
}
  • Related