gpt4 book ai didi

c++ - GoogleTest:从测试访问环境

转载 作者:可可西里 更新时间:2023-11-01 18:39:20 24 4
gpt4 key购买 nike

我正在为 C++(Google 的单元测试框架)尝试 gtest,并且我创建了一个::testing::Environment 子类来初始化和跟踪我的大部分测试所需的一些东西(并且不要' 想要设置不止一次)。

我的问题是:如何实际访问环境对象的内容?我想理论上我可以在我的测试项目中将环境保存在全局变量中,但是有更好的方法吗?

我正在尝试对一些已经存在(非常复杂)的东西进行测试,因此设置非常繁重。

最佳答案

A related question针对创建 std::string 的特定情况处理此问题,给出完整的响应,展示如何使用 google 的::testing::Environment,然后从单元测试内部访问结果。

转载自那里(如果你点赞我,请也点赞他们):

class TestEnvironment : public ::testing::Environment {
public:
// Assume there's only going to be a single instance of this class, so we can just
// hold the timestamp as a const static local variable and expose it through a
// static member function
static std::string getStartTime() {
static const std::string timestamp = currentDateTime();
return timestamp;
}

// Initialise the timestamp in the environment setup.
virtual void SetUp() { getStartTime(); }
};

class CnFirstTest : public ::testing::Test {
protected:
virtual void SetUp() { m_string = currentDateTime(); }
std::string m_string;
};

TEST_F(CnFirstTest, Test1) {
std::cout << TestEnvironment::getStartTime() << std::endl;
std::cout << m_string << std::endl;
}

TEST_F(CnFirstTest, Test2) {
std::cout << TestEnvironment::getStartTime() << std::endl;
std::cout << m_string << std::endl;
}

int main(int argc, char* argv[]) {
::testing::InitGoogleTest(&argc, argv);
// gtest takes ownership of the TestEnvironment ptr - we don't delete it.
::testing::AddGlobalTestEnvironment(new TestEnvironment);
return RUN_ALL_TESTS();
}

关于c++ - GoogleTest:从测试访问环境,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2435277/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com