c++unit-testingarchitecturegoogletestgooglemock

Google mock dependency injection in fixture gives 'invalid new-expression of abstract class type' error


I am trying to create an example of how dependency injection can benefit the current code base I am working on. Part of the example is a demonstration of how DI can benefit the unit testability of the code.

In this example, a compile error is given that I have never seen before: https://godbolt.org/z/3xoKhefYs. I do understand that a virtual function must be implemented.

Looking at the googletest source, the following comment is given for the virtual function of "TestBody()": https://github.com/google/googletest/blob/main/googletest/include/gtest/gtest.h#L326.

Did I miss anything with my implementation of the mock or test? I look forward to your ideas.

I tried the following example in Godbolt: https://godbolt.org/z/3xoKhefYs. My expectation is that it would compile and run. But the error given by the compiler seems to point out an implementation issue with the googletest framework.


Solution

  • The problem is that there are two classes called Test in scope of TestFixture: ::testing::Test (added as injected-class-name) and your ::Test in global scope. When compiler looks up Test, it first finds injected-class-name ::testing::Test and this is an abstract class.

    The solution is simply to rename your struct Test to something else or use ::Test everywhere in TestFixture to make sure compiler chooses your class from global namespace.