Search code examples
c++visual-studiounit-testingprogram-entry-pointgoogletest

How to unit test main() in VisualStudio


Is there a simple way to unit test main() in Visual Studio 2019 in C++?

I've tried #including a main.h and calling main() from the test, but it 'looks' like the test's main() is getting called instead, causing a recursion.

I would like to introduce testing to students very early (write code to make tests green) and the students will have no experience(yet) of functions or classes.

FYI we're using GoogleTest, but that choice can be changed.


Solution

  • main is special, because you can have only one main in the program. Also main isnt something you typically unit test. However, the solution is rather straightforward

    // the "main" function you can test
    int my_main(int argc, char** argv) {
        // ...
    }
    
    // your main (the one you dont include for testing
    int main(int argc, char** argv) {
        return my_main(argc,argv);
    }
    

    and the students will have no experience(yet) of functions or classes

    I have doubts on this strategy. Composability is a precondition for unit-testing. Unit testing makes sense if you have small units that can be tested in isolation. Before being able to unit test main one needs a basic understanding that there are functions that can be called (and tested).