Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gtest capture result of EXPECT_NO_THROW statement

Tags:

c++

googletest

Say I have a method which creates a non-trivially constructable object which is RVO'd back to the caller. For example

MyComplexClass value = deserialize();

deserialize throws an exception on failure, so I want to do something like

EXPECT_NO_THROW(MyComplexClass value = deserialize());

but of course, value goes out of scope (since the macro introduces a try/catch block). And also

MyComplexClass value;
EXPECT_NO_THROW(value = deserialize());

does not work since there is no default constructor (for example it is = delete).

Any ideas on this? I could do something like

template<typename TResult>
TResult return_assert_no_throw(std::function<TResult()> expression)
{
    try
    {
        return expression();
    }
    catch (const std::exception & ex)
    {
        ASSERT_TRUE(false);
    }
}

but this seems a little hacky, and we lose information on the exception

like image 440
yano Avatar asked Oct 21 '25 11:10

yano


1 Answers

An alternative to having a dummy instance is using emplace in a collection:

std::vector<MyComplexClass> v;
EXPECT_NO_THROW(v.emplace_back(deserialize()));
// work with v[0] as the value
like image 187
Daniel Mahu Avatar answered Oct 22 '25 23:10

Daniel Mahu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!