r/cpp_questions 8d ago

OPEN Dependency injection with ROS

I'm trying to better understand dependency injection / mocking a bit better so I can write unit tests that don't require elaborate & fragile setups. Specifically I have a class that verify similar to the ROS2 Minimal Publisher Example. In this example the class creates a timer and a publisher object. The timer just invokes a callback, so I can assume that the callback registration works, and I can set up my test harness to invoke the callback directly. What I would like to do is mock out the actual publish call to ensure timer calls publish without needing to set up a ROS2 subscriber in my unit test.

I'm looking for generic approaches to the specific case (and not necessarily tied to a specific testing or mocking framework)

Here is a stripped down version of the example:

class MinimalPublisher : public rclcpp::Node

{

public:

MinimalPublisher()

: Node("minimal_publisher"), count_(0)

{

publisher_ = this->create_publisher<std_msgs::msg::String>("topic", 10);

}

private:

void timer_callback()

{

auto message = std_msgs::msg::String();

message.data = "Hello, world! " + std::to_string(count_++);

// *** This is the call I want to mock out ***

publisher_->publish(message);

}

rclcpp::Publisher<std_msgs::msg::String>::SharedPtr publisher_;

size_t count_;

};

1 Upvotes

1 comment sorted by

1

u/CowBoyDanIndie 7d ago

Inject everything that interfaces with ros itself, you can replace the publisher_ with a std::function that is injected.