首页 > 解决方案 > rostest 中的时钟似乎没有在简单测试中运行

问题描述

我建立了一个非常简单的测试,例如:

#include <ros/node_handle.h>
#include <gtest/gtest.h>

struct SimpleTicker {

    SimpleTicker(ros::NodeHandle &nh) : _nh(nh) {
       _stateTickTimer = _nh.createTimer(ros::Duration(0.25f),
      &SimpleTicker::incrementVal, this, false, true);
    }

    void incrementVal(const ros::TimerEvent&) {
        val++;
    }

    int val = 0;
    ros::Timer _stateTickTimer;
    ros::NodeHandle _nh;

};


TEST(SlamManagerTest, run_simple_tick) {
    ros::NodeHandle nh(~);
    SimpleTicker s(nh);
    ros::Duration{1}.sleep();
    ASSERT_GT(s.val, 0);
}


int main(int argc, char **argv) 
{
    testing::InitGoogleTest(&argc, argv);
    ros::init(argc, argv, "simple_timer_test");
    ros::NodeHandle nh;
    if (ros::console::set_logger_level(ROSCONSOLE_DEFAULT_NAME, 
                                       ros::console::levels::Debug))
    {
        ros::console::notifyLoggerLevelsChanged(); // show debug output in tests
    }
    return RUN_ALL_TESTS();
}

这个非常简单的测试,启动一个带有计时器的类,该计时器应该回调以每 0.25 秒递增一个值。我用测试文件启动它:

<launch>
  <test test-name="simple_timer_test" pkg="manager" type="simple_timer_test">
  </test>
</launch>

简单地推出

rostest src/manager/test/simple_timer.test

但是测试失败并且该值永远不会增加。我怀疑我设置 rostest 以使用时钟的方式有问题。有什么想法吗?

标签: c++ros

解决方案


所以看起来系统没有旋转。我猜由于运行rostest节点的这种特定方式,永远不要调用 ros::spin() 因为它正忙于运行测试。所以无论哪里需要睡眠,我们都需要旋转,就像这样:

template <typename F>
void spin_sleep(ros::Duration duration, F break_condition) {
    auto end = ros::Time::now() + duration;
    while (end > ros::Time::now() && !break_condition()) {
        ros::spinOnce();
    }
}

void spin_sleep(ros::Duration duration) {
    spin_sleep(duration, []() { return false;});
}

然后代替睡觉做这样的事情:

ros::NodeHandle nh(~);
SimpleTicker s(nh);
spin_sleep(ros::Duration{1});
ASSERT_GT(s.val, 0);

推荐阅读