Search code examples
c++fstreamgoogletest

Google Test methods with fstream


I want to write Google Test for method, that return void and take two arguments: filepath to file1 and filepath to file2. This method read some data in first file and create second file, where does this data write. For this i use std::ifstream and std::ofstream. In test i want call my method and then check, that second file was create:

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

I create file1 and run test. But this test failed, because in method ConvertToBin() -std::basic_ifstream.is_open() failed (return false). Path to file1 exactly true.

#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."));

  ...
}

Even if in my test i create only std::ifstream (don't call converter.ConvertToBin()), having previously created "file2.txt" in my directory, data.is_open() return false too. I'm sure I'm passing the right paths. Really i can't use fstream in GoogleTest? Or am I doing something wrong?

My test class:

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

class ConverterTest : public ::testing::Test {
 protected:
  ConverterTest() = default;
  Converter converter;
};

Solution

  • It's all Ok. In the project build system point uncorrect path to root directory. Thefore path to files were wrong.