c++unit-testingvisual-studio-codegoogletestvs-unit-testing-framework

Need advice on adding test framework (GoogleTest) to a .cpp file having main() function


I am a beginner at testing in CPP and this is my first testing project. I have written a code in CPP and I have to add test cases using any test framework, for which I have decided to use GoogleTest after learning on the internet that it is the most popular and beginner friendly. My .cpp file looks like this...

#inlcude<bits/stdlib.h>
using namespace std;

//fn definitions and declarations 

read_input(){
    //reads input from the user
}
calculate(){
    //processes the input and does calculations
}
print_output(){
    //prints the output
}
    
int main()
{
    read_input();
    calculate();
    print_putput();
  return 0;

}

In the googleTest tutorials, I have seen that the test.cpp is created and there a header file is included and the .cpp file never has a main(), only functions (in this context it would be just the caclculate() function without main() function in cpp... see this example).

I want to ask how can I add tests with google test to a .cpp file that I described above having main(), reads input, and prints output.


Solution

  • One way is to create these files:

    1. func.h: in which you just put declarations of your functions. Example:
    // Only function declarations:
    void read_input();
    void print_output();
    
    1. func.cpp: in which you put the implementation of your functions. This would be similar to what you have but without the main function. This file should include func.h.

    2. main.cpp: in which you only put the main function without anything else. This file should include func.h and can call those functions.

    3. func_test.cpp: in which you put your tests. This file should include func.h and can call and test those functions.

    Your build system should be set such that main.cpp and func_test.cpp do not depend on each other, but they each should depend on func.cpp and get linked with it.

    For examples on using VSCode and Bazel build system with google test, you can check this tutorial. If you use Cmake, you can use this one.