C++单元测试测试,使用模板测试类

C++ unit test testing, using template test class

本文关键字:测试类 单元测试 测试 C++      更新时间:2023-10-16

我正在进行一些C++测试驱动的开发。我有一组做同样事情的类,例如

相同的输入给出相同的输出(或者应该,这就是我试图测试的)。我正在使用Visual Studio 2012的

CppUnitTestFramework。我想创建一个模板化的测试类,所以我只写了一次测试,可以根据需要在类中进行模板化,但我找不到实现这一点的方法。我的目标:

/* 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>
{
};

有没有一种方法可以使用CppUnitTestFramework做到这一点?

有没有其他单元测试框架可以让我这样做?

我不知道是否有办法用CppUnitTestFramework做到这一点,我不熟悉,但你肯定可以在谷歌测试中执行是指定一个任意的类列表,并具有框架为所有这些测试生成(按模板)相同的测试。我认为符合你的要求。

你可以在这里下载谷歌测试作为源代码。

你想要的习语是:

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
}

研究底漆和样本。然后转到AdvancedGuide用于类型测试

还可以查看更多断言

我也遇到过类似的问题:我有一个接口和它的几个实现。当然,我只想针对接口编写测试。此外,我不想为每个实现复制我的测试。

嗯,我的解决方案不是很漂亮,但它很简单,是我迄今为止唯一想出的解决方案。

您可以对Class1和Class2执行同样的操作,然后为每个实现添加更专门的测试。

设置.cpp

#include "stdafx.h"
class VehicleInterface
{
public:
    VehicleInterface();
    virtual ~VehicleInterface();
    virtual bool SetSpeed(int x) = 0;
};
class Car : public VehicleInterface {
public:
    virtual bool SetSpeed(int x) {
        return(true);
    }
};
class Bike : public VehicleInterface {
public:
    virtual bool SetSpeed(int x) {
        return(true);
    }
};

#define CLASS_UNDER_TEST Car
#include "unittest.cpp"
#undef CLASS_UNDER_TEST

#define CLASS_UNDER_TEST Bike
#include "unittest.cpp"
#undef CLASS_UNDER_TEST

unittest.cpp

#include "stdafx.h"
#include "CppUnitTest.h"
#define CONCAT2(a, b) a ## b
#define CONCAT(a, b) CONCAT2(a, b)
using namespace Microsoft::VisualStudio::CppUnitTestFramework;

TEST_CLASS(CONCAT(CLASS_UNDER_TEST, Test))
{
public:
    CLASS_UNDER_TEST vehicle;
    TEST_METHOD(CONCAT(CLASS_UNDER_TEST, _SpeedTest))
    {
        Assert::IsTrue(vehicle.SetSpeed(42));
    }
};

您需要从build.

中排除"unittest.cpp"