返回
ROS2中使用Gtes示例解析,了解Gtes安装使用步骤
开发工具
2023-09-29 12:52:16
一、Gtes简介
Gtes是一个用于编写ROS2单元测试的框架,它基于Google Test和Google Mock。Gtes提供了许多有用的特性,包括:
- 简单易用: Gtes的API与Google Test和Google Mock非常相似,因此很容易学习和使用。
- 强大的断言: Gtes提供了丰富的断言,可以帮助你验证测试结果的正确性。
- 模拟: Gtes提供了模拟框架,可以帮助你模拟ROS2中的各种对象。
- 代码覆盖率: Gtes可以生成代码覆盖率报告,帮助你了解你的测试覆盖了多少代码。
二、安装Gtes
要在ROS2中使用Gtes,你需要先安装它。
sudo apt install ros-<DISTRO>-gtest
其中,<DISTRO>
是你的ROS发行版版本,如galactic
、humble
等。
三、创建测试包
创建一个新的ROS2包来存放你的测试代码。
mkdir ~/ros2_ws/src/gtest_pkg
cd ~/ros2_ws/src/gtest_pkg
在gtest_pkg
包中创建一个CMakeLists.txt文件,内容如下:
cmake_minimum_required(VERSION 3.5)
find_package(ament_cmake REQUIRED)
ament_cmake_export_libraries()
在gtest_pkg
包中创建一个名为test.cpp
的文件,内容如下:
#include <gtest/gtest.h>
TEST(gtest_pkg, test1)
{
ASSERT_EQ(1, 1);
}
在gtest_pkg
包中创建一个名为CMakeLists.txt
的文件,内容如下:
cmake_minimum_required(VERSION 3.5)
find_package(ament_cmake REQUIRED)
find_package(gtest REQUIRED)
ament_package()
ament_target_dependencies()
ament_target_fltk()
add_gtest(gtest_pkg test.cpp)
四、运行测试
cd ~/ros2_ws
colcon build --packages-select gtest_pkg
source install/local_setup.bash
ros2 test gtest_pkg
如果测试通过,你应该会看到如下输出:
[gtest_pkg]
test1 ... passed
[ PASSED ] 1 test, 1 assertion
五、使用Gtes模拟ROS2对象
Gtes提供了模拟框架,可以帮助你模拟ROS2中的各种对象。例如,你可以模拟一个话题,然后向这个话题发送消息。
#include <gtest/gtest.h>
#include <rclcpp/rclcpp.hpp>
class TopicMock : public rclcpp::MockNode
{
public:
MOCK_METHOD(void, publish, (const std::string&, const std::string&));
};
TEST(gtest_pkg, test_publish)
{
auto node = std::make_shared<TopicMock>();
EXPECT_CALL(*node, publish("topic_name", "hello world"));
node->publish("topic_name", "hello world");
}
在上面的代码中,我们创建了一个TopicMock
类,它继承自rclcpp::MockNode
。TopicMock
类提供了一个publish()
方法,它可以模拟向一个话题发送消息。
我们在test_publish()
测试中,使用EXPECT_CALL()
函数来设置对publish()
方法的期望调用。然后,我们调用node->publish()
方法来发送消息。最后,我们使用ASSERT_TRUE()
函数来验证publish()
方法是否被调用了。
六、使用Gtes生成代码覆盖率报告
Gtes可以生成代码覆盖率报告,帮助你了解你的测试覆盖了多少代码。
colcon test --packages-select gtest_pkg --results-dir build/test_results
这将在build/test_results
目录中生成一个代码覆盖率报告。