繁体   English   中英

使用带有 C++ 和 UnitTest++ 的宏

[英]Using Macros with C++ and UnitTest++

I am working on a large C++ project, for safety critical aerospace software, we have about 50 developers working on the project, so of course it is huge, we are using C++ on Red Hat Linux with a little bit of Java and Python, and系统的一小部分也托管在 IBM AIX Unix 和 Windows 上。

我最近被聘用到这个项目中,发现 UnitTest++ 被用于进行单元测试。 让我感到困惑的一件事是 UnitTest++ 如何使用宏。 它使用宏定义派生的 class,然后对宏的调用调用基本 class 方法。 这是非常不寻常的,我试图在一个小例子 C++ 程序中重现同样的事情,但无法让它工作。 注意示例程序的源代码。 由于保密协议,我无法在我们的项目中发布特定代码。

应该有办法让它工作,它在我们的单元测试中使用 UnitTest++

// macro2.cpp

#include <iostream>

using namespace std;

class TestBaseClass
{
    public:

    // class constructor
    TestBaseClass() : num1(3), num2(8)
    {
        cout << "Object Created" << endl;
    }

    // class properties
    int num1;
    int num2;

    // class method
    void testMethod()
    {
        cout << "testMethod() called" << endl;
    }

    // class destructor
    ~TestBaseClass()
    {
        cout << "Object Destroyed" << endl;
    }

};


#define TEST_MACRO(TestBaseClass) \
    class TestDerivedClass : public TestBaseClass \
    { \
        public: \
        TestDerivedClass() { num1 = 10; } \ 
    }; \

int main() 
{

    // call macro base class method
    TEST_MACRO(TestBaseClass)
    {
        testMethod();
    }

    return 0;
}

免责声明:不是 100% 确定 UnitTest++ 是如何做到的,但 Boost 单元测试似乎也在做同样的事情,我想不出还有什么可以做到的。

解决方案是使用 class TestDerivedClass 中的方法签名结束TestDerivedClass ,以便随后的 scope ( { //call to things within TestDerivedClass} ) 用作该方法的实现。

由于您不能在 function scope 中声明 class,因此您还需要通过其他一些结构调用此方法(即,Boost 单元测试也会通过宏生成主方法)

这是一个工作示例:

#include <iostream>

using namespace std;

class TestBaseClass
{
public:

    // class constructor
    TestBaseClass() : num1(3), num2(8)
    {
        cout << "Object Created" << endl;
    }

    // class properties
    int num1;
    int num2;

    // class method
    void testMethod()
    {
        cout << "testMethod() called" << endl;
    }

    // class destructor
    ~TestBaseClass()
    {
        cout << "Object Destroyed" << endl;
    }

};


#define TEST_MACRO(TestBaseClass) \
class TestDerivedClass : public TestBaseClass \
{ \
    public: \
    TestDerivedClass() { num1 = 10; } \
    void testMethodInternal(); \
}; \
   \
void TestDerivedClass::testMethodInternal()

// call macro base class method
TEST_MACRO(TestBaseClass)
{
    testMethod();
}

int main()
{
    TestDerivedClass inst;
    inst.testMethodInternal();
    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM