Google测试C++,调用错误的构造函数的破碎行为

发布于 2025-01-22 20:41:34 字数 686 浏览 1 评论 0原文

我有一个构造函数,可以打开一个文件并抛出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);
}

看似需要的是将构造函数分配给某些东西,这迫使使用适当的构造函数。这是预期的行为吗?

I have a constructor that opens a file and throws a std::runtime_error if it fails, the constructor just takes one argument, the filename with path.I'd like to test it like this;

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

but instead, I have to test it like this as the default, not the single parameter constructor is thrown;

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);
}

What's seemingly required is to assign the constructor to something, which forces the use of the proper constructor. Is this expected behavior?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

握住我的手 2025-01-29 20:41:34

我发现assert_throw()一般而言的宏(通常不会像我期望的那样解析)。我倾向于将测试包裹在lambda中,然后将lambda放在宏中:

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

I find the ASSERT_THROW() macro bothersome in general (it often does not parse the way I expect). I tend to wrap the test in a lambda then place the lambda in the macro:

TEST(TestTextParser, LoadFileThatDoesntExist) {
    auto test = [](){TextParser(brokenFilePath);};
    ASSERT_THROW(test(), std::runtime_error);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文