簡體   English   中英

如何在本機C ++單元測試(Visual Studio)中從項目中打開文件?

[英]How to open a file from the project in a native C++ unit test (Visual Studio)?

我在Visual Studio(2012)中有一個本機C ++單元測試項目。
在我的一個測試中,我想閱讀單元測試項目中包含的文件。 可能嗎? 我應該設置哪些文件屬性以及我應該使用哪條路徑?

我在我的項目中添加了一個test.txt文件(並嘗試將其Content屬性設置為true)。 在單元測試中,我試圖用這樣的相對路徑打開文件:

std::ifstream file("text.txt");

但它不起作用。

我想該文件應該被復制到運行單元測試的地方。 有一個簡單的解決方案嗎?

這可以通過使用__FILE__宏來完成,在我的例子中,我喜歡這樣:

//Returns my solution's directory
#define TEST_CASE_DIRECTORY GetDirectoryName(__FILE__)

string GetDirectoryName(string path){
    const size_t last_slash_idx = path.rfind('\\');
    if (std::string::npos != last_slash_idx)
    {
        return path.substr(0, last_slash_idx + 1);
    }
    return "";
}

TEST_METHOD(MyTest)
{
    string filename = std::string(TEST_CASE_DIRECTORY) + "MyTestFile.txt";

    TestOutputForFile(filename);
}

暫無
暫無

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

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