开发者

googletest: construct fixtures with parameters?

I have two implementations of an algorithm working on arrays and returning a single value, a slow and naive but correct method A and an optimized method B that may be buggy at corners of the input parameter space. Method B has branches depending on the size of the input array and I开发者_StackOverflow中文版'd like to test B against A for different input array sizes. Both methods are templated to work with different types.

I'm just starting to use googletest for the first time, but I don't really see a clear way of how to do this with a fixture (the following is simplified, there is more to set up to get the tests going and I'd also like to run other tests on the data):

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

In the googletest documentation the step to run the actual tests after the fixture definition would be to define the types

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

but this shows the limitation, that only a single template parameter is allowed for classes derived from ::testing::Test. Am I reading this right? How would one go about this?


You can always pack multiple parameter types into a tuple. To pack integer values, you can use type-value converters like this:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜