Domanda

I'm trying to use a single Google Test to test a method. However, the method is overriden by various subclasses. How can I ensure Google Test applies the test to all the methods which override the one I'm testing on? Example:

class Base {
    public:
        virtual void foo() = 0;
}

class Derived : public Base{
    public:
        void foo(){
           /*This is the code I want Google Test to test */
        }
}

class Derived2 : public Base{
    public:
        void foo(){
           /*This is the code I want Google Test to test */
        }
}
È stato utile?

Soluzione

You can use typed tests or type-parameterised tests to do this.

Here's a typed test matching your example:

// A test fixture class template where 'T' will be a type you want to test
template <typename T>
class DerivedTest : public ::testing::Test {
 protected:
  DerivedTest() : derived_() {}
  T derived_;
};

// Create a list of types, each of which will be used as the test fixture's 'T'
typedef ::testing::Types<Derived, Derived2> DerivedTypes;
TYPED_TEST_CASE(DerivedTest, DerivedTypes);

// Create test cases in a similar way to the basic TEST_F macro.
TYPED_TEST(DerivedTest, DoFoo) {
  this->derived_.foo();
  // TypeParam is the type of the template parameter 'T' in the fixture
  TypeParam another_derived;
  another_derived.foo();
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top