Google Unit Test Confusion

2020-05-03 11:14发布

问题:

I'm a bit confused about where the unit tests should be. All the documentation leads me to believe that I must create a Test Project. REALLY? With JUnit we just created a Test package (folder) inside our application project and the tests would run with every build.

I'm new to C++ and trying to figure out how Google Test works. I've found a lot of really good questions and answers here on SO and Yes I have read the Google Test documentation but I'm still confused about this one thing:

Can I create a subfolder in my project with all my unit tests, such that they will execute with each build?

If YES then can you please help me find the needed information/example?

OK, I found in the Primer here: https://github.com/google/googletest/blob/master/googletest/docs/primer.md

Once you are able to compile the Google Test library, you should create a project or build target for your test program. This is promising! Maybe the documentation just keeps mentioning creating a project and doesn't make it clear that the test code can be in your application project?

Nope! Just wishful thinking on my part, as πάντα-ῥεῖ pointed out in his answer.

回答1:

"All the documentation leads me to believe that I must create a Test Project. REALLY?"

Yes with c++ you have to, because there's no generic test runner executable artifact, as it's kind of provided with JUnit.

Can I create a subfolder in my project with all my unit tests, such that they will execute with each build?

I would recommend to put all the test case classes (as plain .cpp sources) into a separate project, and link with the classes under test from a separate library project. Include gtest_all.cc with the main() function, or link against the gtest library, with the test project.

To run the test cases add running the UnitTester artifact build from that project as an additional build step.


"Maybe the documentation just keeps mentioning creating a project and doesn't make it clear that the test code can be in your application project."

Well, that depends a lot upon your actual IDE/build system what is a single project (I prefer to use this term for single artifacts as a result), and a solution (or workspace) for a related collection of them.