3
我想單元測試boost文件系統函數create_directories()的失敗情況,即當create_directory失敗時。有人可以提供任何建議如何做到這一點?另一個要求是代碼需要跨平臺。單元測試升壓文件系統create_directories
我想單元測試boost文件系統函數create_directories()的失敗情況,即當create_directory失敗時。有人可以提供任何建議如何做到這一點?另一個要求是代碼需要跨平臺。單元測試升壓文件系統create_directories
你可以嘗試創建一個路徑的目錄到文件:
#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;
}
非常方便的例子/ – sb32134