2011-10-02 40 views
4

我有两个算法在数组上工作,并返回一个值,一个缓慢而天真但正确的方法A和一个优化的方法B,可能是在输入参数空间的角落错误。方法B有分支取决于输入数组的大小,我想测试B针对A对于不同的输入数组大小。这两种方法都模板化以适应不同类型。googletest:用参数构造灯具?

我刚开始第一次使用googletest,但我并没有真正看到如何用夹具来做到这一点的清晰方法(以下内容已简化,还有更多要设置以获取测试准备,我也想在其上运行的数据等测试):

template<typename T, unsigned int length> // type to test on, test array size 
class BTest : public ::testing:Test { 
    public: 
     T* data; // test data 
    public: 
     BTest(); // allocate data, populate data with random elements 
     ~BTest(); 
     T run_method_a_on_data(); // reference: method A implementation 
}; 
// ... 
TYPED_TEST_CASE(...) // set up types, see text below 

TYPED_TEST(...) { 
    // test that runs method B on data and compares to run_method_a_on_data() 
} 

在googletest文档步骤来运行灯具定义后的实际测试,将是确定的类型

typedef ::testing::Types<char, int, unsigned int> MyTypes; 
TYPED_TEST_CASE(BTest, MyTypes); 

但这显示了限制,只有一个模板参数是允许从::testing::Test派生的类。我正在读这个吗?怎么会这样呢?

回答

6

您始终可以将多个参数类型打包到一个元组中。要打包整数值,您可以使用类型值转换器,如下所示:

template <size_t N> class TypeValue { 
public: 
    static const size_t value = N; 
}; 
template <size_t N> const size_t TypeValue<N>::value; 

#include <tuple> /// Or <tr1/tuple> 
using testing::Test; 
using testing::Types; 
using std::tuple; // Or std::tr1::tuple 
using std::element; 

template<typename T> // tuple<type to test on, test array size> 
class BTest : public Test { 
public: 
    typedef element<0, T>::type ElementType; 
    static const size_t kElementCount = element<1, T>::type::value; 
    ElementType* data; // test data 

public: 
    BTest() { 
    // allocate data, populate data with random elements 
    } 
    ~BTest(); 
    ElementType run_method_a_on_data(); // reference: method A implementation 
}; 
template <typename T> const size_t BTest<T>::kElementCount; 

.... 

typedef Types<tuple<char, TypeValue<10> >, tuple<int, TypeValue<199> > MyTypes; 
TYPED_TEST_CASE(BTest, MyTypes); 
+0

谢谢,那正是我一直在寻找的。 – bbtrb

+1

请注意,对于C++ 11,'element'是'std :: tuple_element','ElementType' typedef看起来像'typedef typename std :: tuple_element <0, T> :: type ElementType'。 – BKewl