我有一个用 C++ 编写的程序,为了确保在进行更改时不会破坏任何内容,我想添加单元测试。
在程序中,我们使用宏来创建某些经常使用的对象。这看起来像:
#define PROPERTY_SWITCHPOINT(var) \
private: \
comp::SwitchPoint* m##var; \
public: \
void set##var(bool val, unsigned short switchIdx = 0) \
{\
if(m##var) m##var->setValue(val,switchIdx); \
}\
bool get##var() \
{\
return (NULL == m##var ? false : m##var->getValue()); \
}\
comp::SwitchPoint* get##var##Ptr() \
{\
return m##var; \
}
在包含切换点的类的标题中,我们调用宏
class Classname
{
private:
PROPERTY_SWITCHPOINT(SwitchpointObject)
}
然后在包含开关点的类的构造函数中,我们执行以下操作:
Classname::Classname()
{
mSwitchpointObject = CreateSwitchpoint("Switchpoint name", 2);
}
comp::SwitchPoint* Classname::CreateSwitchpoint(const std::string& name, unsigned short numberOfSwitches = 1)
{
comp::SwitchPoint* sp = new comp::SwitchPoint(name, true, numberOfSwitches);
return sp;
}
现在我们可以使用mSwitchpointObject->getValue()
来获取这个对象的值了。所有这些都有效,但我无法为它创建单元测试,我使用的是 unittest++ 框架。我用这个测试试过:
#include "UnitTest++.h"
#include "Classname.h"
namespace
{
TEST(SwitchpointTest1)
{
PROPERTY_SWITCHPOINT(SwitchpointObject)
mSwitchpointTestVariabele = CreateSwitchpoint("test switchpoint", 2);
CHECK_EQUAL(mSwitchpointTestVariabele->getValue(), true);
//mSwitchpointTestVariabele->setValue(false, 0);
//CHECK_EQUAL(mSwitchpointTestVariabele->getValue(), false);
//mSwitchpointTestVariabele->setValue(false, 1);
//CHECK_EQUAL(mSwitchpointTestVariabele->getValue(), false);
//mSwitchpointTestVariabele->setValue(true, 0);
//CHECK_EQUAL(mSwitchpointTestVariabele->getValue(), false);
//mSwitchpointTestVariabele->setValue(true, 1);
//CHECK_EQUAL(mSwitchpointTestVariabele->getValue(), true);
}
}
但这给了我编译器错误:
| |In member function 'virtual void<unnamed>::TestSwitchpointTest1::RunImpl() const':|
| 9|error: expected primary-expression before 'private'|
| 9|error: expected ';' before 'private'|
| 9|error: expected primary-expression before 'public'|
| 9|error: expected ';' before 'public'|
| 9|error: a function-definition is not allowed here before '{' token|
| 9|error: a function-definition is not allowed here before '{' token|
|10|error: 'mSwitchpointTestVariabele' was not declared in this scope|
|10|error: 'CreateSwitchpoint' was not declared in this scope|
| |=== Build finished: 8 errors, 0 warnings ===|
我猜问题是宏创建了需要测试的代码的一部分,并且在创建这部分之前执行了单元测试,但是从 Aleguna 的回复中我知道这不是问题所在。
我应该如何为这样的代码编写测试?