如何在本地c++单元测试(Visual Studio)中打开项目中的文件

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

本文关键字:项目 文件 Studio Visual c++ 单元测试      更新时间:2023-10-16

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