Time out for test cases in googletest

断了今生、忘了曾经 提交于 2019-11-30 13:28:26

问题


Is there a way in gtest to have a timeout for inline/test cases or even tests. For example I would like to do something like: EXPECT_TIMEOUT(5 seconds, myFunction());

I found this issue googletest issues as 'Type:Enhancement' from Dec 09 2010. https://code.google.com/p/googletest/issues/detail?id=348

Looks like there is no gtest way from this post. I am probably not the first to trying to figure out a way for this.

The only way I can think is to make a child thread run the function, and if it does not return by the time limit the parent thread will kill it and show timeout error.

Is there any way where you don't have to use threads? Or any other ways?


回答1:


I just came across this situation.

I wanted to add a failing test for my reactor. The reactor never finishes. (it has to fail first). But I don't want the test to run forever.

I followed your link but still not joy there. So I decided to use some of the C++14 features and it makes it relatively simple.

But I implemented the timeout like this:

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.
}

Now that I have my failing test I can write the code that fixes the test.



来源:https://stackoverflow.com/questions/25852389/time-out-for-test-cases-in-googletest

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!