2011-12-01 81 views
4

我試圖從構造函數聲明(帶有參數)正常類創建一個測試夾具類,如下圖所示:谷歌測試 - 構造函數聲明錯誤

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文件中。任何方式來做到這一點? 我曾嘗試在很多方面實施它,但迄今尚未取得成功。有關如何實現這一點的任何建議?

+0

你能解釋一下使用這個類的問候嗎?這個班是否正在測試?我想是這樣。你能寫出代碼來顯示你想如何使用類helloTestFixture來測試你好嗎? – Baltasarq

+0

是的,你好是正在測試的類,helloTestFixture是它的'TestFixture'類。我在這裏面臨的問題是,我無法像在實際類中所做的那樣初始化Fixture類中的構造函數,這正是我的主要問題。我將添加一個測試來展示我打算如何通過helloTestFixture訪問hello類。 – Emulator

+0

但是,@Emulator,這是非常棘手的問題:如果您打算使用TEST_F,則無法爲參數提供構造函數。編譯錯誤與helloTestFixture類有關,該類沒有默認的構造函數,這就是TEST_F宏需要創建一個對象。如果你仔細想想,如果構造函數不是默認構造函數(他不知道要傳遞什麼參數),TEST_F不可能創建類的對象。我認爲你應該解決創建helloTestFixtureClass所需的對象的問題,正如我的答案中所暴露的那樣。 – Baltasarq

回答

2

沒有多少碼校正之後,這裏就是我在商店要告訴你:的回答 :)

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

這編譯和運行很好,並希望這回答了你的問題。 :)

3

這個錯誤告訴你,你不是在helloTestFixture類中提供一個默認的構造函數,這個宏需要使用TEST_F宏來創建你的類的對象。

您應該使用部分關係而不是is-a。創建您需要的類hello的所有對象,以測試您需要的所有各個方面。

我不是Google Test的專家。然而,在這裏瀏覽文檔:

http://code.google.com/p/googletest/wiki/Primer#Test_Fixtures:_Using_the_Same_Data_Configuration_for_Multiple_Te

http://code.google.com/p/googletest/wiki/FAQ#Should_I_use_the_constructor/destructor_of_the_test_fixture_or_t

看來,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功能的努力,也將刪除對象以防出現問題。

希望這會有所幫助。

+0

試過了。這種方式並不真正起作用。感謝您的輸入。 – Emulator

+0

我要爲您的問題添加評論。那麼我肯定我不明白這個問題本身。 – Baltasarq