谷歌测试-构造函数声明错误

Google Test - Constructor declaration error

本文关键字:声明 错误 构造函数 测试 谷歌      更新时间:2023-10-16

我试图从一个普通类与构造函数声明(带参数)创建一个测试夹具类,如下所示:

hello.h

class hello
{
public:
hello(const uint32_t argID, const uint8_t argCommand);
virtual ~hello();
void initialize();
};

其中uint32_t为:typedef unsigned int, uint8_t为:typedef unsigned char

My Test Fixture Class:

helloTestFixture.h

class helloTestFixture:public testing::Test
{
public:
helloTestFixture(/*How to carry out the constructor declaration in this test fixture class corresponding to the above class?*/);
virtual ~helloTestFixture();
hello m_object;
    };
TEST_F(helloTestFixture, InitializeCheck) // Test to access the 'intialize' function
{
m_object.initialize();
}
在尝试实现上面的代码后,它给了我错误:
 Error C2512: no appropriate default constructor available

我试图复制在hello.h文件中构造的构造函数到我的hellotestfixture.h文件。有什么办法吗?我已经尝试了很多方法来实现它,但到目前为止还没有成功。对如何实现这一点有什么建议吗?

此错误告诉您,您没有在helloTestFixture类中提供默认构造函数,TEST_F宏需要该构造函数来创建您的类的对象。

应该使用part-of关系,而不是使用is-a。创建您需要的类hello的所有对象,以便测试您需要的所有各个方面。

我不是Google Test的专家。但是,在这里浏览文档:

https://github.com/google/googletest/blob/master/googletest/docs/primer.md test-fixtures-using-the-same-data-configuration-for-multiple-tests

https://github.com/google/googletest/blob/master/googletest/docs/faq.md should-i-use-the-constructordestructor-of-the-test-fixture-or-setupteardown

似乎SetUp方法是首选的。如果您的目标是测试类hello,您可以这样写:

#include <memory>
#include "hello.h"
#include "gtest.h"
class TestHello: public testing::Test {
public:
    virtual void SetUp()
    {
        obj1.reset( new hello( /* your args here */ ) );
        obj2.reset( new hello( /* your args here */ ) );
    }
    std::auto_ptr<hello> obj1;
    std::auto_ptr<hello> obj2;
};
TEST_F(QueueTest, MyTestsOverHello) {
    EXPECT_EQ( 0, obj1->... );
    ASSERT_TRUE( obj2->... != NULL);
}

auto_ptr并不是真正需要的,但是它将为您节省编写TearDown函数的精力,并且它还将在出现错误时删除对象。

在没有太多的代码更正之后,以下是我为您准备的内容:一个答案:)

class hello
{
public:
  hello(const uint32_t argID, const uint8_t argCommand);
virtual ~hello();
void initialize();
};
hello::hello(const uint32_t argID, const uint8_t argCommand){/* do nothing*/}
hello::~hello(){/* do nothing*/}
void hello::initialize(){/* do nothing*/}
class helloTestFixture
{
public:
  helloTestFixture();
  virtual ~helloTestFixture();
  hello m_object;
};
helloTestFixture::helloTestFixture():m_object(0,0){/* do nothing */}
helloTestFixture::~helloTestFixture(){/* do nothing */}
int main()
{
    helloTestFixture htf;
    htf.m_object.initialize();
}

编译和运行得很好,希望这能回答你的问题。:)