簡體   English   中英

Google Test C++ 中的錯誤行為,調用了錯誤的構造函數

[英]Broken behavior in Google Test C++, calling wrong constructor

我有一個構造函數,它打開一個文件並在失敗時拋出一個 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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM