Home > Software engineering >  Is there a way to expect global exception in GTest?
Is there a way to expect global exception in GTest?

Time:09-23

I have a scenario where a call SendFeedback() sends a message and returns successfully. The message is received by another thread which throws. EXPECT_THROW doesn't work because SendFeedback() does not throw itself. Is there a way to expect this kind of exceptions?

pseudo-code:

auto listener = Listener();
auto sender = Sender();
...
sender.SendFeedback();

// listener throws due to unexpected feedback. This exception is to be expected

CodePudding user response:

It is not exactly what you asked for, but GTest have for mechanism for death tests, where you can assert that given invocation would crash the program. Uncaught exception invokes std::terminate, which by default invokes std::abort, thus will pass the assertion.

I've made small proof of concept to verify it works:

void delayed_uncaught_exception()
{
    using namespace std::chrono_literals;
    std::thread thread([] { throw std::runtime_error("Error"); });
    std::this_thread::sleep_for(50ms);
}

TEST(MyDeathTest, DelayedException)
{
    ASSERT_DEATH(delayed_uncaught_exception(), "");
}

Although, I strongly agree with discussion under the question, that death tests maybe not the best fit for this test scenario and in long-run I'd recommend redesigning the flow.

CodePudding user response:

I wrote similar test programs for a communication library. I used an independent communication channel for sending the result back to the gtest thread. The receiver thread has to catch the exception and send the result back to the gtest thread of process. This communication channel can be just a global variable or some kind of message queue, but the 2 threads have to be synchronized. I found barriers useful for that.

  • Related