How to use inheritance for a class with TEST_CLASS in CppUnitTestFramework
Asked Answered
R

2

10

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,

Reprography answered 26/6, 2014 at 7:6 Comment(0)
C
12

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!

Concerted answered 27/5, 2015 at 5:48 Comment(0)
M
1

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.

Meter answered 26/6, 2014 at 8:40 Comment(1)
Thanks TobiMcNamobi. Composition is not possible in this instance due to the class of the test iterating the methods of the class. I may have to change testing frameworks to get this to work correctly.Reprography

© 2022 - 2024 — McMap. All rights reserved.