【问题标题】:In Google Test, can I call GetParam() from the constructor?在 Google 测试中,我可以从构造函数中调用 GetParam() 吗?
【发布时间】:2018-11-27 23:11:49
【问题描述】:

Google Test C++ 单元测试框架提供了执行parameterised tests 的能力。要访问给定测试的参数,文档告诉我派生一个子类并调用GetParam()

class FooTest : public ::testing::TestWithParam<const char*> {
  // You can implement all the usual fixture class members here.
  // To access the test parameter, call GetParam() from class
  // TestWithParam<T>.
};

我在文档或源代码中找不到比这更具体的内容(据我了解)。

我可以在哪里(或何时)致电GetParam()?我知道我可以在 TEST_P(...) { ... } 宏的主体中调用它,但是呢:

  • SetUp() 方法中FooTest()?
  • FooTest()的构造函数中?
  • FooTest()的初始化列表中?

【问题讨论】:

    标签: c++ googletest


    【解决方案1】:

    是的,你可以。 你可以假设GetParam()::testing::TestWithParam 基类的方法。

    class FooTest : public ::testing::TestWithParam<const char*> {
      std::string name;
      FooTest() : name(GetParam()) {} 
    };
    

    使用C++11 - 你甚至可以直接在类中初始化成员:

    class FooTest : public ::testing::TestWithParam<const char*> {
      std::string name = GetParam();
    };
    

    【讨论】:

    • 哦,不错(C++11 语法,我不知道)。我很困惑,因为虽然我知道我可以将 GetParam() 视为基类方法,但我不确定 何时 无论 GetParam() 返回是否已初始化(例如,在构造时或稍后通过一些 GTest 魔法)。
    • 您可能会假设 - 当您开始构建成员时,已经构建了基类 - 在此处阅读更多信息:stackoverflow.com/questions/7539282/…
    猜你喜欢
    • 2014-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-23
    • 1970-01-01
    • 2011-07-10
    相关资源
    最近更新 更多