Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Googletest does not accept temporary object in EXPECT_THROW

I have a class that has no default constructor, but the constructor may throw. I was wanting to have a test like:

EXPECT_THROW(MyClass(param), std::runtime_error);

But the compiler, g++, complains that there is no default constructor for MyClass. However, the following...

EXPECT_THROW(MyClass foo(param), std::runtime_error);

...works, and the test passes as expected. Why though won't Googletest accept the temporary object?

class MyClass
{
public:
  MyClass(std::string const& filename);
  //...
};

Interestingly enough, I had refactored my test to not have the filename in a separate variable, and when asked to check I found the following works:

EXPECT_THROW(MyClass("somefilename"), std::runtime_error);

However the following doesn't:

std::string filename("somefilename");
EXPECT_THROW(MyClass(filename), std::runtime_error);
like image 418
thumper Avatar asked Jun 22 '11 23:06

thumper


1 Answers

If you're hit with the "most vexing parse", the cure is often uniform initialization:

EXPECT_THROW(MyClass{param}, std::runtime_error);

(assuming your compiler understands C++11).

like image 179
Bulletmagnet Avatar answered Sep 28 '22 09:09

Bulletmagnet