gpt4 book ai didi

tdd - 如何在Google测试中为多个测试初始化​​常量字符串?

转载 作者:行者123 更新时间:2023-12-04 13:49:12 24 4
gpt4 key购买 nike

我正在使用Google测试,并且我有一个包含多个测试的cpp文件。我想在开始第一次测试时用当前的日期和时间初始化一个字符串。我也想在所有其他测试中使用此字符串。我怎样才能做到这一点。

我已经尝试了以下操作(m_stringCnFirstTest的 protected 成员),但是它没有用(因为在每次测试之前都会调用构造函数和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
}

最佳答案

您可以使用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();
}

关于tdd - 如何在Google测试中为多个测试初始化​​常量字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30593762/

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