Search code examples
c++unit-testingcmakegoogletest

find external test file for unit test by relative path c++ cmake guest


What would be the proper way to access an external test file for the unit test of a c++ project? I am using CMake and Gtest.

This is a sample of the directory structure.

Project
   -src
       -test (unit tests here)
   -test-data (data file here)

Thanks!


Solution

  • Pass the file name to gtest arguments:

    add_executable(foo ...)
    enable_testing()
    add_test(FooTest foo "${CMAKE_CURRENT_LIST_DIR}/data/input.file")
    

    get the parameter after gtest parse input:

    int main(int argc, char** argv) {
      ::testing::InitGoogleTest(&argc, argv);
      assert(argc == 2); // gtest leaved unparsed arguments for you
    

    and save it to some global *:

      file_name = argv[1];
      return RUN_ALL_TESTS();
    

    * Usually it's not a very good idea to pollute the global namespace but I think it's fine for testing app

    Related