Search code examples
c++unit-testinginheritancevisual-studio-2013cppunit

How to use inheritance for a class with TEST_CLASS in CppUnitTestFramework


I've got a class that inherits from another class like so:

class TestClass : public BaseClass

I am wondering if it is possible to make this a test class using the TEST_CLASS macro or some other macro that is part of the Microsoft Unit Testing Framework for C++. I tried:

class TEST_CLASS(TestClass : public BaseClass)

But the IDE gives the error 'Error: expected either a definition or a tag name' and the compiler error is error C3861: '__GetTestClassInfo': identifier not found

I know it's probably bad practice to inherit on a test class but it would make implementing the test easier. I am relatively new to C++ so I am wondering if it is something simple I have missed or if it's just not possible.

Thanks,


Solution

  • There is one other option you didn't include and others may be tripping over this question without knowing the solution.

    You can actually derive from any arbitrary type by looking at the macro itself:

    ///////////////////////////////////////////////////////////////////////////////////////////
    // Macro to define your test class. 
    // Note that you can only define your test class at namespace scope,
    // otherwise the compiler will raise an error.
    #define TEST_CLASS(className) \
    ONLY_USED_AT_NAMESPACE_SCOPE class className : public ::Microsoft::VisualStudio::CppUnitTestFramework::TestClass<className>
    

    As C++ supports multiple inheritance you can easily derive by using code similar to the following:

    class ParentClass
    {
    public:
        ParentClass();
        virtual ~ParentClass();
    };
    
    TEST_CLASS(MyTestClass), public ParentClass
    {
    };
    

    Just remember that if you are working with resources you will need to have a virtual destructor to have it be called. You will also have to call the initialize & cleanup methods directly if you are going to be using them, because the static methods they create are not called automagically.

    Good luck, Good testing!