Simplest example of using Google C++ Testing Framework with CMake
Asked Answered
G

2

27

I have a very simple C++ library (one header file, one .cpp file). I want to write unit tests for this project using the Google C++ Testing Framework.

Here is the directory structure:

~/project1
 |
 |-- project1.cpp
 |-- project1.h
 |-- project1_unittests.cpp
 \-- CMakeLists.txt

I do not plan to write my own main() function. I want to link with gtest_main as mentioned in the primer. What should CMakeLists.txt contain?

Grannias answered 5/5, 2011 at 15:37 Comment(0)
P
26

Enable CMake's built-in testing subsystem:

# For make-based builds, defines make target named test.
# For Visual Studio builds, defines Visual Studio project named RUN_TESTS.
enable_testing()

Compile an executable that will run your unit tests and link it with gtest and gtest_main:

add_executable(runUnitTests
    project1_unittests.cpp
)
target_link_libraries(runUnitTests gtest gtest_main)

Add a test which runs this executable:

add_test(
    NAME runUnitTests
    COMMAND runUnitTests
)
Petrarch answered 5/5, 2011 at 17:0 Comment(3)
Thank you very much. This helped a lot. I had to link with both gtest, gtest_main and pthread. I also had to specify absolute paths for libgtest.a and libgtest_main.a; is there a better way to add these static libraries to the linker search path?Grannias
Got it! I set and exported GTEST_ROOT in bash and then include_directories($ENV{GTEST_ROOT}/include) with link_directories($ENV{GTEST_ROOT}).Grannias
In my case, I chose to add the subdirectory gtest-1.6.0, since this wasn't working for me (no -lgtest found). I used #8508223 and got things working.Threesome
H
0

Here is a simplest one,

1.Create a simple source file,

$ cat simplegtest.cpp 

#include<gtest/gtest.h>
TEST(Mytest, failing_test){
    EXPECT_TRUE(false);
}

2.Compile it using below command,

$ LDLIBS="-lgtest_main -lgtest" make simplegtest
g++     simplegtest.cpp  -lgtest_main -lgtest -o simplegtest

3.Execute the test executable using below command,

$ ./simplegtest 
Running main() from /home/prashant/work/thirdparty/googletest-release-1.8.1/googletest/src/gtest_main.cc
[==========] Running 1 test from 1 test case.
[----------] Global test environment set-up.
[----------] 1 test from Mytest
[ RUN      ] Mytest.failing_test
simplegtest.cpp:4: Failure
Value of: false
  Actual: false
Expected: true
[  FAILED  ] Mytest.failing_test (0 ms)
[----------] 1 test from Mytest (0 ms total)

[----------] Global test environment tear-down
[==========] 1 test from 1 test case ran. (1 ms total)
[  PASSED  ] 0 tests.
[  FAILED  ] 1 test, listed below:
[  FAILED  ] Mytest.failing_test

 1 FAILED TEST
Hemiterpene answered 22/4, 2021 at 19:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.