Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Separate test cases across multiple files in google test

Tags:

c++

googletest

I'm new in google test C++ framework. It's quite easy to use but I'm wondering how to separate the cases into multiple test files. What is the best way?

Include the .cpp files directly is an option. Using a header seems that does nothing...

Any help is welcome

like image 866
Killrazor Avatar asked Sep 16 '11 11:09

Killrazor


People also ask

Does Google test run tests in parallel?

gtest-parallel is a script that executes Google Test binaries in parallel, providing good speedup for single-threaded tests (on multi-core machines) and tests that do not run at 100% CPU (on single- or multi-core machines).

What is test fixture in Google test?

If you find yourself writing two or more tests that operate on similar data, you can use a test fixture. This allows you to reuse the same configuration of objects for several different tests. To create a fixture: Derive a class from ::testing::Test .

What is Gtest_main?

It includes a trivial main method that will launch the registered tests, something like this (as of 1.8): GTEST_API_ int main(int argc, char **argv) { printf("Running main() from gtest_main.cc\n"); testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }


2 Answers

Create one file that contains just the main to run the tests.

// AllTests.cpp #include "gtest/gtest.h"  int main(int argc, char **argv) {     testing::InitGoogleTest(&argc, argv);     return RUN_ALL_TESTS(); } 

Then put the tests into other files. You can put as many tests as you like in a file. Creating one file per class or per source file can work well.

// SubtractTest.cpp #include "subtract.h" #include "gtest/gtest.h"  TEST(SubtractTest, SubtractTwoNumbers) {     EXPECT_EQ(5, subtract(6, 1)); } 

This does require that all tests can share the same main. If you have to do something special there, you will have to have multiple build targets.

like image 56
Wayne Johnston Avatar answered Sep 20 '22 03:09

Wayne Johnston


Not looking for credits or points. I'm new to stackoverflow and don't have the the reputation to add comments. @jkoendev's answer despite being technically correct makes an incorrect statement "I think the main missing point in the other answer is that you need to #include the test files." Not true, you just need to link all the CPP files together.

For example in CMAKE

add_executable(${PROJECT_NAME}      ${sources}     ${headers}) 

along with a

file(GLOB_RECURSE sources     ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp) 

links all the cpp files. You don't need to include any of the test files in the main file.

like image 23
rstr1112 Avatar answered Sep 23 '22 03:09

rstr1112