googletest中的测试用例超时

时间:2014-09-15 16:13:32

标签: googletest

gtest中有没有办法让内联/测试用例甚至测试超时。 例如,我想做的事情如下:           EXPECT_TIMEOUT(5秒,myFunction());

我从2010年12月9日发现此问题googletest问题为“类型:增强”。 https://code.google.com/p/googletest/issues/detail?id=348

看起来这篇文章没有gtest方式。 我可能不是第一个试图找到解决方法的人。

我能想到的唯一方法是让子线程运行该函数,如果它没有返回 时间限制,父线程将终止它并显示超时错误。

有没有办法不用线程? 还是其他任何方式?

1 个答案:

答案 0 :(得分:3)

我刚刚遇到过这种情况。

我想为我的反应堆添加一个失败的测试。反应堆永远不会完成。 (它必须首先失败)。但我不希望测试永远运行。

我跟着你的链接,但仍然不喜欢那里。所以我决定使用一些C ++ 14的功能,这使它相对简单。

但我实现了这样的超时:

TEST(Init, run)
{
    // Step 1 Set up my code to run.
    ThorsAnvil::Async::Reactor                      reactor;
    std::unique_ptr<ThorsAnvil::Async::Handler>     handler(new TestHandler("test/data/input"));
    ThorsAnvil::Async::HandlerId                    id = reactor.registerHandler(std::move(handler));

    // Step 2
    // Run the code async.
    auto asyncFuture = std::async(
        std::launch::async, [&reactor]() {
                               reactor.run();   // The TestHandler
                                                // should call reactor.shutDown()
                                                // when it is finished.
                                                // if it does not then 
                                                // the test failed.
                            });

    // Step 3
    // DO your timeout test.
    EXPECT_TRUE(asyncFuture.wait_for(std::chrono::milliseconds(5000)) != std::future_status::timeout);

    // Step 4
    // Clean up your resources.
    reactor.shutDown();             // this will allow run() to exit.
                                    // and the thread to die.
}

现在我的测试失败,我可以编写修复测试的代码。

相关问题