Skip to content

Commit 7095ef1

Browse files
authored
Testing with GTest Tutorial (ros2#3359)
Signed-off-by: David V. Lu <[email protected]>
1 parent 3d250b9 commit 7095ef1

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
.. TestingCpp:
2+
3+
Writing Basic Tests with C++ with GTest
4+
=======================================
5+
6+
Starting point: we'll assume you have a :ref:`basic ament_cmake package<CreatePkg>` set up already and you want to add some tests to it.
7+
8+
In this tutorial, we'll be using `gtest <https://google.github.io/googletest/primer.html>`__.
9+
10+
Package Setup
11+
-------------
12+
13+
Source Code
14+
^^^^^^^^^^^
15+
We'll start off with our code in a file called ``test/tutorial_test.cpp``
16+
17+
.. code-block:: c++
18+
19+
#include <gtest/gtest.h>
20+
21+
TEST(package_name, a_first_test)
22+
{
23+
ASSERT_EQ(4, 2 + 2);
24+
}
25+
26+
int main(int argc, char** argv)
27+
{
28+
testing::InitGoogleTest(&argc, argv);
29+
return RUN_ALL_TESTS();
30+
}
31+
32+
33+
package.xml
34+
^^^^^^^^^^^
35+
Add the following line to ``package.xml``
36+
37+
.. code-block:: c++
38+
39+
<test_depend>ament_cmake_gtest</test_depend>
40+
41+
CMakeLists.txt
42+
^^^^^^^^^^^^^^
43+
44+
.. code-block:: cmake
45+
46+
if(BUILD_TESTING)
47+
find_package(ament_cmake_gtest REQUIRED)
48+
ament_add_gtest(${PROJECT_NAME}_tutorial_test test/tutorial_test.cpp)
49+
target_include_directories(${PROJECT_NAME}_tutorial_test PUBLIC
50+
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
51+
$<INSTALL_INTERFACE:include>
52+
)
53+
ament_target_dependencies(${PROJECT_NAME}_tutorial_test
54+
std_msgs
55+
)
56+
target_link_libraries(${PROJECT_NAME}_tutorial_test name_of_local_library)
57+
endif()
58+
59+
The testing code is wrapped in the ``if/endif`` block to avoid building tests where possible. ``ament_add_gtest`` functions much like ``add_executable`` so you'll need to call ``target_include_directories``, ``ament_target_dependencies`` and ``target_link_libraries`` as you normally would.
60+
61+
62+
Running Tests
63+
-------------
64+
65+
See the :doc:`tutorial on how to run tests from the command line <CLI>` for more information on running the tests and inspecting the test results.

source/Tutorials/Intermediate/Testing/Testing-Main.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,4 +39,5 @@ Available Tutorials:
3939
:maxdepth: 1
4040

4141
CLI
42+
Cpp
4243
Python

0 commit comments

Comments
 (0)