c++unit-testingtemplatesvisual-c++microsoft-cpp-unit-test

C++ unit test testing, using template test class


I’m doing some C++ test driven development. I have a set of classes the do the same thing e.g.

same input gives same output (or should, that’s what I’m try to test). I’m using Visual Studio 2012’s

CppUnitTestFramework. I wanted to create a templated test class, so I write the tests once, and can template in classes as needed however I cannot find a way to do this. My aim:

/* two classes that do the same thing */
class Class1
{
    int method()
    {
        return 1;
    }
};

class Class2
{
    int method()
    {
        return 1;
    }
};

/* one set of tests for all classes */
template< class T>
TEST_CLASS(BaseTestClass)
{
    TEST_METHOD(testMethod)
    {
        T obj;

        Assert::AreEqual( 1, obj.method());
    }
};

/* only have to write small amout to test new class */
class TestClass1 : BaseTestClass<Class1>
{
};

class TestClass2 : BaseTestClass<Class1>
{
};

Is there a way I can do this using CppUnitTestFramework?

Is there another unit testing framework that would allow me to do this?


Solution

  • I do not know if there is a way to do this with CppUnitTestFramework, with which I am unfamiliar, but something you can certainly do in googletest is specify an arbitrary list of classes and have the framework generate (template-wise) the same test(s) for all of them. I think that would fit your bill.

    You can download googletest as source here.

    The idiom you will want is:

    typedef ::testing::Types</* List of types to test */> MyTypes;
    ...
    TYPED_TEST_CASE(FooTest, MyTypes);
    ...
    TYPED_TEST(FooTest, DoesBlah) {
        /*  Here TypeParam is instantiated for each of the types
            in MyTypes. If there are N types you get N tests.
        */
        // ...test code
    }
    
    TYPED_TEST(FooTest, DoesSomethingElse) {
        // ...test code
    }
    

    Study the primer and the samples. Then go to the AdvancedGuide for Typed Tests

    Also check out More Assertions