katang
katang

Reputation: 2764

How can I subclass gtest testing::Test?

I have test classes with some common functionality, and I want to create something like

class BaseTest : public testing::Test

then derive further subclasses, like

class StuffTest : public BaseTest

However, the compiler gives the error message

error: use of deleted function 'StuffTest::StuffTest()'
TEST_F(StuffTest, SFile)

How can I derive test subclass, and why this strange error message?

Added some test code: (I want to add a test name in the subclasses. Without constructor, it works OK. With constructor I experience weird syntax errors.)

#include <gtest/gtest.h>

using namespace std;

// A new test class  of these is created for each test
class BaseTest
  : public testing::Test
{
public:
 // BaseTest(string a);
BaseTest();
   virtual void SetUp()
   { cerr << "Setting up " << MyName;}
   virtual void TearDown()
   {cerr << "Closing down " << MyName;}
protected:
  string MyName;
};


//BaseTest::BaseTest(string TestName)
BaseTest::BaseTest()
: testing::Test
{
//  MyName = TestName;
}

TEST_F(BaseTest, Tools)
{
  cerr << "Something was wrong\n";
}


// A new test class  of these is created for each test
class MyStuffTest : BaseTest
{
public:
};
/*
TEST_F(MyStuffTest, Tools)
{
  cerr << "Something was wrong\n";
}
*/


int main(int argc, char **argv) {
  testing::InitGoogleTest(&argc, argv);
   return RUN_ALL_TESTS();
}

Upvotes: 3

Views: 4815

Answers (1)

Marko Popovic
Marko Popovic

Reputation: 4153

I am not sure where you intended to call the constructors with std::string arguments in the first place, usage of googletest fixture classes does not imply explicit creation of fixture class objects. The problem is that you are trying to create a fixture class without a default constructor (it is not generated by the compiler because you declared one with a std::string argument). This is an issue because googletest creates a new class for each test declared with TEST_F(MyFixtureClass, ...), this new class inherits from MyFixtureClass and needs the default constructor.

To obtain the name of the test, use testing::TestInfo object which can be retrieved using method testing::UnitTest::current_test_info. For a more detailed usage example, check the documentation.

Upvotes: 3

Related Questions