Google Test c++的错误行为,调用错误的构造函数



我有一个构造函数,它打开一个文件,如果失败则抛出std::runtime_error,构造函数只接受一个参数,带路径的文件名。我想这样测试一下;

TEST(TestTextParser, LoadFileThatDoesntExist) {
ASSERT_THROW(TextParser(brokenFilePath),std::runtime_error);
}

但是,我必须像这样测试它作为默认值,而不是抛出单参数构造函数;

TEST(TestTextParser, LoadFileThatDoesntExist) {
try {
auto c = TextParser(brokenFilePath);
EXPECT_TRUE(false);
}
catch(std::runtime_error e)
{
std::cout << e.what() << std::endl;
ASSERT_TRUE(e.what() == ("Unable to open file " + brokenFilePath));
return;
}
EXPECT_TRUE(false);
}

似乎需要的是将构造函数赋值给某物,这强制使用正确的构造函数。这是预期行为吗?

我发现ASSERT_THROW()宏通常很麻烦(它通常不按我期望的方式进行解析)。我倾向于将测试封装在lambda中,然后将lambda放在宏中:

TEST(TestTextParser, LoadFileThatDoesntExist) {
auto test = [](){TextParser(brokenFilePath);};
ASSERT_THROW(test(), std::runtime_error);
}

最新更新