From: https://google.github.io/googletest/advanced.html#sharing-resources-between-tests-in-the-same-test-suite。我使用1.11 googletest版本。
我试图在以下测试中利用此功能:Game_test.h
class Game_test : public :: testing :: Test
{
protected:
Game_test() = default;
virtual ~Game_test() = default;
public:
void SetUpTestCase()
{
Field field(8, 8);
Engine engine;
Rules rules;
GameLogic glogic(&engine, &rules, &field);
}
};
cpp:我期望它会自动为每个TEST_F运行SetUpTestCase(),但它没有。我错过了什么?
TEST_F(Game_test, apply_rule)
{
field.setStatus(1, 2, true); // use of undeclared identifier.....
}
注:最初我使用SetUpTestSuite(),后来我尝试了SetUpTestCase(),这是在示例
几点:
- 示例是
SetUpTestSuite
,不是SetUpTestCase
。 SetUpTestSuite
应该是静态成员field
如果在SetUpTestSuite
中使用,应该是类的静态成员。SetUpTestSuite
每个测试套件运行一次,而不是每个测试用例运行一次。- 如果你想在每个测试用例中运行一次,使用
SetUp
,这是一个非静态成员函数。 SetUp
可以操作非静态成员变量。
下面的例子展示了这两个函数的用法:
class Game_test : public testing::Test {
protected:
Game_test() = default;
virtual ~Game_test() = default;
public:
static void SetUpTestSuite() {
std::cout << "========Beginning of a test suit ========" << std::endl;
static_field = std::string("AAAA");
}
void SetUp() override {
std::cout << "========Beginning of a test ========" << std::endl;
object_field = std::string("AAAA");
}
static std::string static_field;
std::string object_field;
};
std::string Game_test::static_field;
TEST_F(Game_test, Test1) {
EXPECT_EQ(static_field, std::string("AAAA"));
EXPECT_EQ(object_field, std::string("AAAA"));
// We change object_field, SetUpTestSuite cannot reset it back to "AAAA" because
// it only runs once at the beginning of the test suite.
static_field = std::string("BBBB");
// Although we change object_field here,
// SetUp will reset it back to "AAAA" at the beginning of each test case.
object_field = std::string("BBBB");
}
TEST_F(Game_test, Test2) {
EXPECT_EQ(static_field, std::string("BBBB"));
EXPECT_EQ(object_field, std::string("AAAA"));
}
实例:https://godbolt.org/z/e6Tz1xMr1