Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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,

like image 873
Willem van Ketwich Avatar asked Jun 26 '14 07:06

Willem van Ketwich


2 Answers

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!

like image 199
Bob_Gneu Avatar answered Nov 15 '22 17:11

Bob_Gneu


It's been a while since I used CppUnitTestFramework but back then this site has been a valuable resource for many questions on that topic.

TEST_CLASS is preprocessor macro. You can use it to declare a test class like

TEST_CLASS(className)
{
    TEST_METHOD(methodName) 
    {
        // test method body
    }
    // and so on
}

That's it. As far as I know there is no way to inherit test classes from one another.

Maybe though composition over inheritance might help in your specific case.

like image 34
TobiMcNamobi Avatar answered Nov 15 '22 17:11

TobiMcNamobi