【问题标题】:Google unit testing in C++: how to write a persistent data file?C++ 中的 Google 单元测试:如何编写持久数据文件?
【发布时间】:2017-11-29 13:52:58
【问题描述】:

问题:

1) 由 C++ Google 单元测试创​​建的文件放在哪里?

2) 有没有办法在 C++ Google 单元测试中写入持久数据文件,以便在测试运行后可以访问该文件?

代码和期望的行为

我正在使用 catkin_make 在 Ubuntu 14.04 上运行单元测试。我希望代码在测试运行后可以找到的某个地方编写一个文件。下面的代码写了一个文件,但是我不知道它去哪里了,或者它在单元测试完成后是否仍然存在。

TEST(GUnitTestFileIo, Test_One)
{
  std::ofstream csvFile;
  csvFile.open("helloWorldTestFile.csv");
  if (csvFile.is_open()) {
    csvFile << "Hello, World, !" << std::endl;
    csvFile.close();
  } else {
    std::cout << "Failed to open the file!" << std::endl;
  }
}

int main(int argc, char **argv){
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

【问题讨论】:

  • 寻求调试帮助的问题(“为什么这段代码不起作用?”)必须包括所需的行为、特定的问题或错误以及在问题本身中重现它所需的最短代码。没有明确问题陈述的问题对其他读者没有用处。请参阅:如何创建 minimal reproducible example。使用“编辑”链接改进您的问题 - 不要通过 cmets 添加更多信息。谢谢!
  • 你只是模糊地解释你已经实现了什么。很难说这里发生了什么。从这个意义上说:尝试一下,如果您可以压缩一个包含您正在做的所有相关信息的小(但有效)示例片段。
  • 这在很大程度上取决于您如何调用生成的可执行文件。是 MSVC 集成吗?测试?自己运行?

标签: c++ unit-testing persistence googletest file-writing


【解决方案1】:

一种解决方案是简单地写入绝对文件路径。以下代码从 google 单元测试内部将文件写入用户的主目录:

TEST(GUnitTestFileIo, Test_One)
{
  char const* tmp = getenv( "HOME" );
  if ( tmp == NULL ) {
    std::cout << "$(HOME) environment variable is not defined!";
  } else {
    std::string home( tmp );  // string for the home directory
    std::ofstream csvFile;  // write the file
    csvFile.open(home + "/helloWorldTestFile.csv");
    if (csvFile.is_open()) {
      csvFile << "Hello, World, !" << std::endl;
      csvFile.close();
    } else {
      std::cout << "Failed to open the file!" << std::endl;
    }
  }
}

// Run all the tests that were declared with TEST()
int main(int argc, char **argv){
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-04
    • 1970-01-01
    • 2014-12-18
    • 1970-01-01
    • 2017-06-06
    • 2012-07-16
    相关资源
    最近更新 更多