简体   繁体   English

如何通过单元测试(使用 CMake 和 GTest)知道测试数据的文件夹在哪里?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM