[英]How to get unit tests (using CMake and GTest) to know where a folder of test data is?
I am using CMake and GTest to unit test a C++ program.我正在使用 CMake 和 GTest 对 C++ 程序进行单元测试。 One of my tests uses
fopen()
to open a file of test data.我的一个测试使用
fopen()
打开一个测试数据文件。
I am struggling to figure out how to not get a "No such file or directory" error.我正在努力弄清楚如何避免出现“没有这样的文件或目录”错误。
Directory Structure目录结构
├── CMakeLists.txt
├── build
├── src
│ └── myProgram.cxx
└── tests
├── CMakeLists.txt
├── data
│ ├── dataset1.txt
│ ├── dataset2.txt
│ ├── dataset3.txt
│ └── dataset4.txt
└── myProgramTests.cxx
Test Code测试代码
TEST(test, read_data_file) {
// Open test file
std::FILE *f = fopen("inputs/dataset1.txt", "r");
if (f == NULL){
perror ("Error opening file");
}
fclose(f);
}
This seems simple, but I can't figure out what to put here.这看起来很简单,但我不知道该放在这里什么。 I have tried
"dataset1.txt"
, "inputs/dataset1.txt"
, "tests/inputs/dataset1.txt"
.我试过
"dataset1.txt"
、 "inputs/dataset1.txt"
、 "tests/inputs/dataset1.txt"
。 What am I missing / is there a way for me into "include" these files via a line in CMakeLists.txt
so I can just read them in with one of the strings I tried above?我错过了什么/有没有办法让我通过
CMakeLists.txt
中的一行“包含”这些文件,这样我就可以用上面尝试过的字符串之一读入它们?
Summary : How do I properly reference the location of files stored in a tests/data
subdirectory within GTest?摘要:如何正确引用存储在 GTest 中的
tests/data
子目录中的文件位置?
Use ctest of cmake. Its add_test
command has a useful property WORKING_DIRECTORY
that are you looking for.使用cmake的 ctest。它的
add_test
命令有一个有用的属性WORKING_DIRECTORY
,您正在寻找它。
Paths that do not start with a /
are relative to your current working directory, ie the directory your shell is in when you run the tests.不以
/
开头的路径是相对于当前工作目录的,即运行测试时 shell 所在的目录。
For example, if your current working directory is the top-level directory of your project, then the relative path to dataset1.txt
is tests/data/dataset1.txt
比如你当前的工作目录是你项目的顶层目录,那么
dataset1.txt
的相对路径就是tests/data/dataset1.txt
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.