c++ - 单元测试 Boost 文件系统 create_directories

标签 c++ unit-testing boost-filesystem

我想对 boost 文件系统函数 create_directories() 的失败案例进行单元测试,即当 create_directory 失败时。有人可以就如何执行此操作提供任何建议吗?另一个要求是代码需要跨平台。

最佳答案

您可以尝试在文件路径中创建一个目录:

#include <fstream>
#include <iostream>
#include "boost/filesystem/path.hpp"
#include "boost/filesystem/operations.hpp"

namespace bfs = boost::filesystem;

int main() {
  // Create test dir
  boost::system::error_code ec;
  bfs::path test_root(bfs::unique_path(
      bfs::temp_directory_path(ec) / "%%%%-%%%%-%%%%"));
  if (!bfs::create_directory(test_root, ec) || ec) {
    std::cout << "Failed creating " << test_root << ": " << ec.message() << '\n';
    return -1;
  }

  // Create file in test dir
  bfs::path test_file(test_root / "file");
  std::ofstream file_out(test_file.c_str());
  file_out.close();
  if (!bfs::exists(test_file, ec)) {
    std::cout << "Failed creating " << test_file << ": " << ec.message() << '\n';
    return -2;
  }

  // Try to create directory in test_file - should fail
  bfs::path invalid_dir(test_file / "dir");
  if (bfs::create_directory(invalid_dir, ec)) {
    std::cout << "Succeeded creating invalid dir " << invalid_dir << '\n';
    return -3;
  }

  // Try to create nested directory in test_file - should fail
  bfs::path nested_invalid_dir(invalid_dir / "nested_dir");
  if (bfs::create_directories(nested_invalid_dir, ec)) {
    std::cout << "Succeeded creating nested invalid dir " << invalid_dir << '\n';
    return -4;
  }

  // Clean up
  bfs::remove_all(test_root);
  return 0;
}

关于c++ - 单元测试 Boost 文件系统 create_directories,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13317721/

相关文章:

c++ - 为公共(public)指数 e 设置默认值并获得 n 作为 key 对的模数

c++ - 在 Visual Studio 2012 中为我的 C++ 项目设置 Aquila

c++ - 成员函数实例化

c++ - boost::filesystem::unicode 文件路径的路径?

c++ - 从数组中的文件中读取多个 float

c# - 手动将 RedirectToRouteResult 解析为查看结果

调试构建类型的 Android 单元测试失败

c++ - 提升文件系统,需要帮助理解我在做什么

c++ - parent_path()带有或不带有斜杠

java - 文件解析和翻译的单元测试