gpt4 book ai didi

c++ - 如何在 native C++ 单元测试 (Visual Studio) 中打开项目中的文件?

转载 作者:太空狗 更新时间:2023-10-29 21:02:15 25 4
gpt4 key购买 nike

我在 Visual Studio (2012) 中有一个 native 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);
}

关于c++ - 如何在 native C++ 单元测试 (Visual Studio) 中打开项目中的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15874723/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com