【问题标题】:How to use gtest to count the number of test classes?如何使用 gtest 统计测试类的数量?
【发布时间】:2022-09-27 10:33:59
【问题描述】:

我试图计算测试类的数量,如下所示:

int classCount = 0;
class TestClass2 : public testing::Test {
protected:
    static void SetUpTestCase() {

    }
    static void TearDownTestCase() {

    }

    virtual void SetUp() { classCount++; }
    virtual void TearDown() {}
};

TEST(TestClass1, classCount) {
    cout << typeid(*this).name() << endl;
    EXPECT_EQ(1, classCount);
}

不幸的是,classCount 为 0。我期待在初始化 TestClass1_xxxx 类时,classCount 将由virtual void SetUp() { classCount++; } +1。但实际上它没有被调用。我在virtual void SetUp() { classCount++; } 中添加了cout,但仍然看不到控制台输出。

所以我的问题是,virtual void SetUp() {} 何时开始调用?它是否以某种方式自动调用?

  • 在现代 C++ 中应该是 void SetUp() override {}

标签: c++ class installation count googletest


【解决方案1】:

您可以删除整个类,代码仍然可以编译。

int classCount = 0;

TEST(TestClass1, classCount) {
    cout << typeid(*this).name() << endl;
    EXPECT_EQ(1, classCount);
}

因为class TestClass2 是一个测试夹具类,应该与宏TEST_F 一起使用。

int classCount = 0;
class TestClass2 : public testing::Test {
protected:
    static void SetUpTestCase() {

    }
    static void TearDownTestCase() {

    }

    void SetUp() override { classCount++; }
    void override TearDown() {}
};

TEST_F(TestClass1, classCount) {
    cout << typeid(*this).name() << endl;
    EXPECT_EQ(1, classCount);
}

你真正的问题是什么?该代码闻起来有XY problem 的味道。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-22
    • 2017-04-06
    • 1970-01-01
    • 2022-07-31
    相关资源
    最近更新 更多