Google Test - Ошибка объявления конструктора - PullRequest
4 голосов
/ 01 декабря 2011

Я пытаюсь создать класс тестового прибора из обычного класса с объявлением конструктора (с аргументами), как показано ниже:

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

Класс моего тестового прибора:

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 . Есть ли способ сделать это? Я пытался реализовать его во многих отношениях, но пока безуспешно. Любые предложения о том, как это реализовать?

Ответы [ 2 ]

3 голосов
/ 01 декабря 2011

Эта ошибка говорит о том, что вы не предоставляете конструктор по умолчанию в классе helloTestFixture, необходимый макросу TEST_F для создания объекта вашего класса.

Вам следует использоватьОтношение часть- вместо 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, и он также удалит объект в случае, если что-то пойдет не так.

Надеюсь, это поможет.

2 голосов
/ 02 декабря 2011

После небольшого исправления кода, вот что у меня есть для вас в магазине: Ответ :)

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();
}

Это компилируется и работает хорошо, и надеюсь, что это ответит на вашивопрос.:)

...