Posted by Rico's Nerd Cluster on November 30, 2024
Use cases
Passing ROS Arguments to ROS2 Test Executables
When writing integration tests in ROS2, you may need to pass command-line parameters (--ros-args -p <param>:=<value>) to your test binaries. By default, GTest’s main() intercepts all arguments, so ROS2 parameters aren’t automatically applied. Follow these steps to forward ROS arguments into your tests:
Provide a Custom main(). Override GTest’s default entry point and initialize both GTest and rclcpp with the original arguments:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include<gtest/gtest.h>
#include<rclcpp/rclcpp.hpp>
#include<vector>
#include<string>// Store all of main()’s argv into a global for laterstaticstd::vector<std::string>g_test_args;intmain(intargc,char**argv){::testing::InitGoogleTest(&argc,argv);g_test_args.assign(argv,argv+argc);rclcpp::init(argc,argv);intret=RUN_ALL_TESTS();rclcpp::shutdown();returnret;}
Forward Arguments in Your Test Fixture. In your fixture’s SetUp(), pass the captured arguments into NodeOptions so your node picks up any --ros-args parameters:
1
2
3
4
5
6
7
8
9
10
11
12
voidSetUp()override{rclcpp::NodeOptionsoptions;options.arguments(g_test_args);options.parameter_overrides({...});node_=std::make_shared<rclcpp::Node>("test_node",options);// Declare and retrieve your own parameternode_->declare_parameter("visualize",false);node_->get_parameter("visualize",visualize_);}
Run Your Test with ROS Args. Finally, invoke your test binary with: ./test_integrate_imu --ros-args -p visualize:=true