Time out for test cases in googletest

余生长醉 提交于 2019-11-30 09:40:44

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.

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