我尝试GTEST用于C ++(谷歌的单元测试框架),和我创建了一个测试:: ::环境的子类初始化并保留一些东西,我需要为我大部分的测试(和不希望的轨道设置不止一次)。
我的问题是:我如何实际访问的环境对象的内容?我想我可以在理论上保护环境,在我的测试项目中的全局变量,但有没有更好的办法?
我试图使一些已经存在的(很纠结)测试的东西,所以设置是相当沉重的。
使用全局变量似乎是推荐的方式,根据Google Test Documentation:
::testing::Environment* const foo_env = ::testing::AddGlobalTestEnvironment(new FooEnvironment);
跟这个有related question交易创建std::string
,给人展示了如何使用谷歌的测试:: ::环境,然后从一个单元测试内部访问结果的全面响应的具体情况。
从那里复制(如果你给予好评我,请给予好评他们太):
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();
}