Home > Mobile >  How to get unit tests (using CMake and GTest) to know where a folder of test data is?
How to get unit tests (using CMake and GTest) to know where a folder of test data is?

Time:10-07

I am using CMake and GTest to unit test a C program. One of my tests uses fopen() to open a file of test data.

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". 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?

Summary: How do I properly reference the location of files stored in a tests/data subdirectory within GTest?

CodePudding user response:

Paths that do not start with a / are relative to your current working directory, i.e the directory your shell is in when you run the tests.

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

CodePudding user response:

Use ctest of cmake. Its add_test command has a useful property WORKING_DIRECTORY that are you looking for.

  • Related