How to test an EXE with Google Test?

后端 未结 6 1406
梦毁少年i
梦毁少年i 2020-12-03 05:55

I have a C++ project in Visual Studio, and have added another project exclusively for testing. Both of these projects are EXEs (console apps). So how do I use the first proj

6条回答
  •  情深已故
    2020-12-03 06:22

    If you are not very rigid about having the tests in a different project, you can write the tests in your application project. Then just make the application execute the tests when receiving certain command line arguments, and execute the normal application logic otherwise, i.e.

    int main(int argc, char* argv[])
    {
        if (argc >= 2 && std::string(argv[1]) == "--tests")
        {
            ::testing::InitGoogleTest(&argc, argv);
            return RUN_ALL_TESTS();
        }
        else
        {
            // Application logic goes here
        }
    }
    
    TEST(ExampleTests, TestSQRTCalculation) // assuming all the right headers are included
    {
        EXPECT_NEAR(2.0, std::sqrt(4.0), 0.000001);
    }
    

    This avoids creating an unnecessary library for the sole purpose of testing, although you can still do it if it is correct structure-wise. The downside is that the testing code goes into the executable you are going to release. If you don't want that I guess you need an additional configuration which specifies a pre-processor directive to disable the tests.

    Debugging the tests or running them automatically at post build is easy, simply by specifying "--tests" as debug args or at post build command line respectively.

提交回复
热议问题