我正在使用谷歌测试,我有一个包含多个测试的cpp文件。我想在开始第一次测试时用当前日期和时间初始化一个字符串。我也希望在所有其他测试中使用此字符串。我怎么能这样做。
我尝试了以下内容(m_string
是CnFirstTest
的受保护成员),但它不起作用(因为构造函数和SetUp
将在每次测试之前调用) :
CnFirstTest::CnFirstTest(void) {
m_string = currentDateTime();
}
void CnFirstTest::SetUp() {
}
TEST_F(CnFirstTest, Test1) {
// use m_string
}
TEST_F(CnFirstTest, Test2) {
// use m_string, too
}
答案 0 :(得分:9)
您可以使用gtest testing::Environment
来实现此目的:
#include <chrono>
#include <iostream>
#include "gtest/gtest.h"
std::string currentDateTime() {
return std::to_string(std::chrono::steady_clock::now().time_since_epoch().count());
}
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.
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();
}