0

is it possible to define a base test-fixture with (abstract) test cases and derive classes from them?

There are two szenarios I'd like to support (Taken from Roy Overshores "The art of Unit Testing"):

  1. Template test class pattern Define abstract test cases in the base test-fixture and thus force derived classes to implement them.
  2. Abstract test driver class pattern Implement tests in the base class that all derived class inherit automatically

I cannot figure out how this works with googletest. If I have a base class

#pragma once class BaseClass : public ::testing::Test { }; TEST_F(BaseClass, T1) { } 

and two derived classes (in different files)

#include "stdafx.h" #include "BaseClass.h" class DerivedClass1 : public BaseClass { }; 

and

#include "stdafx.h" #include "BaseClass.h" class DerivedClass2 : public BaseClass { }; 

I get the compiler error

virtual void __thiscall BaseClass_T1_Test::TestBody(void)" (?TestBody@BaseClass_T1_Test@@EAEXXZ) already defined in DerivedClass1.obj 

Is it somehow possible to define concrete and pure virtual tests in a test base class?

1

1 Answer 1

1

Try move TEST_F(BaseClass, T1){} out of the BaseClass.h into its own .cpp file. The BaseClass.h is included into 2 .cpp files of DerivedClass1 and DerivedClass2, and during compilation the TEST_F will be expanded to a bunch of executable functions that would be included into both of these .cpp files. And that is why the linker is unhappy and complain about the duplication of symbol TestBody@BaseClass_T1_Test@@EAEXXZ).

Sign up to request clarification or add additional context in comments.

2 Comments

Yeah, then it compiles. But the test is not executed for each derived class but only once. Because it is contained in a derived class by itself. I fear I'll have to do an ugly workaround like defining pure virtual methods in the BaseClass that I call from tests of the DerivedClasses
You have to provide more detail example about your code, or it would be difficult to help. Perhaps raise another question in SO.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.