未调用 googletest 设置方法

googletest SetUp Method not called

我正在使用 Google Test 对我的 C++ 项目进行单元测试。入门指南说:

If necessary, write a default constructor or SetUp() function to prepare the objects for each test. A common mistake is to spell SetUp() as Setup() with a small u - don't let that happen to you.

SetUp() 拼写正确,但我仍然无法使 SetUp 正常工作。有什么想法吗?

#include "gtest/gtest.h"

class SampleTest : public ::testing::Test {
 protected:
  virtual void SetUp() { std::cout << "SetUp called." << std::endl; }
};

TEST(SampleTest, OneEqualsOne) {
  int one = 1;
  ASSERT_EQ(1, one);
}

int main(int argc, char **argv) {
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

g++ -g -Wno-deprecated -I gtest/include SampleTest.cpp gtest/libgtest.a -o SampleTest

输出:

[==========] Running 1 test from 1 test case.
[----------] Global test environment set-up.
[----------] 1 test from SampleTest
[ RUN      ] SampleTest.OneEqualsOne
[       OK ] SampleTest.OneEqualsOne (1 ms)
[----------] 1 test from SampleTest (1 ms total)

[----------] Global test environment tear-down
[==========] 1 test from 1 test case ran. (1 ms total)
[  PASSED  ] 1 test.

TEST 更改为 TEST_F,因为 SetUp 方法等是用 TEST_F 调用的,而不是单独用 TEST 调用的。

将您的 TEST 宏更改为 TEST_F。 (它列在您提供的报价下方的文档中。)