遇见gtest--函数参数化测试

本文详细介绍了如何利用gtest的INSTANTIATE_TEST_CASE_P宏进行函数参数化测试,包括宏的参数含义以及如何定义和使用ParamGenerator。文章以一个简单的示例展示了如何设置和运行参数化测试,并指出gtest还支持类型参数化的测试,这部分将在后续内容中进一步探讨。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、前言
      有时为了完整的测试一个函数的正确性,我们需要测试给定各种不同输入的情况下,函数的输出是否正确。最直接的方法就是我们手动去给不同输入,然后测试输出是否正确。但是这种方式工作量大,并且都是重复性,无意义的操作。为此,gtest中提供了参数化的测试。

2、参数化测试使用方法
    要使用参数化测试,我们需要创建一个子类继承testing::TestWithParam<T>,此处T为我们的参数类型。首先我们看一下这个类的声明:
template <typename T>
class TestWithParam : public Test, public WithParamInterface<T> {
};

    它是一个继承自testing::Test类和testing::WithParamInterface<T>的类,接下来我们再看看testing::WithParamInterface<T>这个接口的声明:
template <typename T>
class WithParamInterface {
 public:
  typedef T ParamType;
  virtual ~WithParamInterface() {}

  // The current parameter value. Is also available in the test fixture's
  // constructor. This member function is non-static, even though it only
  // references static data, to reduce the opportunity for incorrect uses
  // like writing 'WithParamInterface<bool>::GetParam()' for a test that
  // uses a fixture whose parameter type is int.
  const ParamType& GetParam() const {
    GTEST_CHECK_(parameter_ !&
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值