C++单元测试测试,使用模板测试类
C++ unit test testing, using template test class
我正在进行一些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.
相关文章:
- 在C++单元测试上下文中,抽象基类是否应将其他抽象基类作为函数参数
- 在类 gtest/gmock 进行单元测试时模拟成员函数C++
- 如何使用私有构造函数对类进行单元测试?
- Visual Studio 2010 单元测试:无法识别引用的项目类
- 单元测试类无法在我要测试的同一解决方案中的另一个项目中找到类
- 冰山类和谷歌单元测试
- 替换 Dll 中的类以进行单元测试
- Boost单元测试夹具继承测试类,是否可以访问受保护的方法
- 更改单元测试的类功能的正确方法
- 当要测试的类很复杂时,如何编写单元测试
- 什么是单元测试模板化 c++ 方法/类/函数的好方法
- 从单元测试.EXE项目引用VC++.EXE项目中的类
- 在函数/类声明附近编写C++单元测试
- Arduino-使用VS2015进行简单的基于类的单元测试
- 无法创建mock类/对象来替换我的类中的私有成员对象的功能,以便在gtest中进行单元测试
- C++单元测试测试,使用模板测试类
- 如何最好地对使用boost::asio::yield_context的类进行单元测试
- 如何为一些类(如timer类)编写单元测试
- 单元测试Arduino类
- 使用boost::filesystem添加头文件后,不再发现来自google测试的单元测试