模板类型化方法 GTesting

Template Typed Method GTesting

这是我的:

/* Can't change 'base' struct. */
struct base {
  public:
    template<typename T>
    void printVal() {
      std::cout << T::x << std::endl;
    }
};

struct testFixture
  : public base
  , public ::testing::Test {
  using base::printVal;
};

TEST_F(testFixture, testF) {
  printVal<A>();
  printVal<B>();
  printVal<C>();
}

效果很好。但是,我想使用类型化测试,所以代码看起来更像这样:

/* Same base class as above. */
struct testFixture
  : public base
  , public ::testing::Test {
  using base::printVal;
};

typedef ::testing::Types<A, B, C> MyTypes;
TYPED_TEST_CASE(testFixture, MyTypes);

TYPED_TEST(testFixture, typedTest) { 
  printVal<TypeParam>();
}

当然,因为 'testFixture' 不是模板化的 struct/class,这不会起作用,我得到这个错误:

test2.cpp:31:12: error: unknown template name 'testFixture'
TYPED_TEST(testFixture, typedTest) {

有没有办法使用 googletest 获得此类功能?

想通了。

'templatize' 夹具:

template <typename T>
struct testFixture
  : public base
  , public ::testing::Test {
  using base::printVal;
  void printVal() {
    base::printVal<T>();
  }
};

然后照常进行:

typedef ::testing::Types<A, B, C> MyTypes;
TYPED_TEST_CASE(testFixture, MyTypes);

TYPED_TEST(testFixture, typedTest) {
  this->template printVal<TypeParam>();
}