Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specify constructor arguments for a Google test Fixture

With Google test I want to specify a Test fixture for use in different test cases. The fixture shall allocate and deallocate objects of the class TheClass and its data management class TheClassData, where the data management class requires the name of a datafile.
For the different tests, the file name should vary.

I defined the following Fixture:

class TheClassTest : public ::testing::Test {
 protected:
  TheClassTest(std::string filename) : datafile(filename) {}
  virtual ~TheClassTest() {}
  virtual void SetUp() {
    data = new TheClassData(datafile);
    tc = new TheClass(data);
  }
  virtual void TearDown() {
    delete tc;
    delete data;
  }

  std::string datafile;
  TheClassData* data;
  TheClass* tc;
};

Now, different tests should use the fixture with different file names. Imagine this as setting up a test environment.

The question: How can I specify the filename from a test, i.e. how to call a non-default constructor of a fixture?

I found things like ::testing::TestWithParam<T> and TEST_P, which doesn't help, as I don't want to run one test with different values, but different tests with one fixture.

like image 362
Gregor Avatar asked Jul 05 '16 15:07

Gregor


1 Answers

As suggested by another user, you cannot achieve what you want by instantiating a fixture using a non-default constructor. However, there are other ways. Simply overload the SetUp function and call that version explicitly in the tests:

class TheClassTest : public ::testing::Test {
protected:
    TheClassTest() {}
    virtual ~TheClassTest() {}
    void SetUp(const std::string &filename) {
        data = new TheClassData(filename);
        tc = new TheClass(data);
    }
    virtual void TearDown() {
        delete tc;
        delete data;
    }

    TheClassData* data;
    TheClass* tc;
};

Now in the test simply use this overload to set up filename:

TEST_F(TheClassTest, MyTestCaseName)
{
    SetUp("my_filename_for_this_test_case");

    ...
}

The parameterless TearDown will automatically clean up when the test is complete.

like image 185
Marko Popovic Avatar answered Oct 14 '22 22:10

Marko Popovic