带有fstream的Google测试方法

问题描述 投票:-1回答:1

我想为方法编写Google Test,该方法返回void并接受两个参数:file1的文件路径和file2的文件路径。此方法读取第一个文件中的一些数据并创建第二个文件,该数据写入哪里。为此,我使用std::ifstreamstd::ofstream。在测试中,我想调用我的方法,然后检查是否创建了第二个文件:

TEST_F(ConverterTest, Convert) {
  converter.ConvertToBin(std::string("file1.txt"), std::string("file2.txt"));
  std::ifstream data("file2.txt");
  EXPECT_TRUE(data.is_open());
}

我创建file1并运行测试。但是此测试失败,因为方法ConvertToBin()-std::basic_ifstream.is_open()失败(返回false)。 file1的路径完全正确。

#include <fstream>
void Converter::ConvertToBin(const std::string& src_path,
                             const std::string& dst_path) {
  input_stream_ = std::ifstream(src_path, std::ios::in);
  if (!input_stream_.is_open())
    throw(std::string("Error."));

  output_stream_ = std::ofstream(dst_path,
                                 std::ios::binary | std::ios::out);
  if (!output_stream_.is_open())
    throw(std::string("Error."));

  ...
}

即使在我的测试中,我只创建了std::ifstream(不要调用converter.ConvertToBin()),并且之前在我的目录中创建了“ file2.txt”,但data.is_open()也返回false。我确定我走的路正确。真的不能在GoogleTest中使用fstream吗?还是我做错了?

我的测试班:

#include <gtest/gtest.h>
#include "src/converter/converter.h"

class ConverterTest : public ::testing::Test {
 protected:
  ConverterTest() = default;
  Converter converter;
};
c++ fstream googletest
1个回答
0
投票

都好。在项目构建系统中,指向根目录的路径不正确。文件的前述路径错误。

© www.soinside.com 2019 - 2024. All rights reserved.