2015-04-01 105 views
5

我想用gtest測試模板類。我在gtest手冊中閱讀了關於TYPED_TEST的文章,並查看了他們引用的官方示例(samples\sample6_unittest.cc)。該示例中的該模板只有一個模板參數。 但是,我的代碼有兩個模板參數,我該如何測試它?如何使用gtest測試具有多個模板參數的C++模板類?

我有以下代碼:

// two element type 
template <typename E, typename F> 
class QueueNew 
{ 
public: 
    QueueNew() {} 
    void Enqueue(const E& element) {} 
    E* Dequeue() {} 
    F size() const 
    { 
     return (F)123; 
    } 
}; 

爲此我寫了下面的測試代碼:

template <class E, class F> 
QueueNew<E, F>* CreateQueue(); 

template <> 
QueueNew<int, int>* CreateQueue<int, int>() 
{ 
    return new QueueNew < int, int > ; 
} 
template <> 
QueueNew<char, char>* CreateQueue<char, char>() 
{ 
    return new QueueNew < char, char > ; 
} 

template <class E, class F> 
class QueueTestNew; 

template <class E> 
class QueueTestNew<E, int> : public testing::Test 
{ 
protected: 
    QueueTestNew() : queue(CreateQueue<E, int>()){} 
    virtual ~QueueTestNew(){ delete queue; } 
    QueueNew<E, int>* const queue; 
}; 

template <class E> 
class QueueTestNew<char, E> : public testing::Test 
{ 
protected: 
    QueueTestNew() : queue(CreateQueue<char, E>()){} 
    virtual ~QueueTestNew(){ delete queue; } 
    QueueNew<char, E>* const queue; 
}; 

// The list of types we want to test. 
typedef ::testing::Types <char, int> Implementations; 

TYPED_TEST_CASE(QueueTestNew, Implementations); 

TYPED_TEST(QueueTestNew, DefaultConstructor) 
{ 
    EXPECT_EQ(123u, this->queue->size()); 
} 

但是建立的時候,我得到的錯誤:

error C2976: 'QueueTestNew' : too few template arguments 
see declaration of 'QueueTestNew' 
... 

我認爲我的測試模板方法與gtest是錯誤的,那麼我應該怎麼做呢?

+0

可以定義一個類型,比如有多個類型定義爲一個結構你的每個亞型。然後讓'QueueTestNew'通過該結構進行類型參數化(嵌套附加模板參數)。 – SleuthEye 2015-04-01 03:16:12

+0

對不起,我不明白。 – thinkerou 2015-04-01 03:40:29

回答

8

一個技巧是讓gtest看到一個單一的類型參數,嵌套類型。要做到這一點,你可以定義一個模板結構,如:

template <typename A, typename B> 
struct TypeDefinitions 
{ 
    typedef typename A MyA; 
    typedef typename B MyB; 
}; 

,你可以傳給你的類型,測試夾具:

template <class T> 
class QueueTestNew : public testing::Test 
{ 
protected: 
    QueueTestNew() : queue(CreateQueue<typename T::MyA, typename T::MyB>()){} 
    virtual ~QueueTestNew(){ delete queue; } 
    QueueNew<typename T::MyA, typename T::MyB>* const queue; 
}; 

// The list of types we want to test. 
typedef ::testing::Types <TypeDefinitions<char,char>, 
          TypeDefinitions<int,int> > Implementations; 

TYPED_TEST_CASE(QueueTestNew, Implementations); 

TYPED_TEST(QueueTestNew, DefaultConstructor) 
{ 
    typename TypeParam::MyA someA; // if you need access to the subtypes in the test itself 

    EXPECT_EQ(123u, this->queue->size()); 
} 
+0

哦,布拉沃。明白了,thx非常!模板和類型名稱非常強大! – thinkerou 2015-04-01 03:53:36

相關問題