【问题标题】:googletest: construct fixtures with parameters?googletest:用参数构造夹具?
【发布时间】:2011-10-02 17:48:21
【问题描述】:

我有两个处理数组并返回单个值的算法实现,一个缓慢而幼稚但正确的方法A 和一个优化的方法B,它可能在输入参数空间的角落有问题。方法B 有分支,具体取决于输入数组的大小,我想针对不同的输入数组大小测试BA。两种方法都被模板化以适用于不同的类型。

我刚刚开始第一次使用 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 派生的类只允许使用单个模板参数。我读对了吗?怎么办?

【问题讨论】:

    标签: c++ unit-testing googletest


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢,这正是我想要的。
    • 请注意,对于 C++11,elementstd::tuple_elementElementType typedef 看起来像 typedef typename std::tuple_element&lt;0, T&gt;::type ElementType
    猜你喜欢
    • 1970-01-01
    • 2016-11-07
    • 2013-02-11
    • 1970-01-01
    • 1970-01-01
    • 2018-12-11
    • 2011-02-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多