我正在为C ++(Google的单元测试框架)尝试gtest,并且我创建了一个:: testing :: Environment子类来初始化并跟踪我的大多数测试所需的一些东西(并且不要我想不止一次设置。
我的问题是:我如何实际访问Environment对象的内容?我想我理论上可以在我的测试项目中将环境保存在全局变量中,但有更好的方法吗?
我正在尝试对已经存在的(非常纠结的)内容进行测试,因此设置非常繁重。
答案 0 :(得分:3)
::testing::Environment* const foo_env = ::testing::AddGlobalTestEnvironment(new FooEnvironment);
答案 1 :(得分:0)
在创建std::string
的特定情况下,related question处理此问题,给出完整的响应,显示如何使用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();
}