谷歌测试:如何为多个测试只运行一次夹具?
Google Test: How to run fixture only once for multiple tests?
我正在尝试使用 gtest 测试 http 客户端。我想用我自己的 http 服务器测试这个客户端。我有一个小型的python服务器。测试用例将是客户端向此 python 服务器发送各种请求。有没有办法在所有测试运行之前启动服务器并在测试后销毁该服务器?
我正在尝试使用如下所示的gtest夹具;通过在SetUp中创建一个新进程并在TearDown中杀死它。但看起来这些调用是针对每个测试进行的。
class Base: public ::testing::Test {
public:
pid_t child_pid = 0;
void SetUp() {
char *cmd = "/usr/bin/python";
char *arg[] = {cmd, "./http_server.py", NULL};
child_pid = fork();
if ( child_pid == 0) {
execvp(cmd, arg);
std::cout << "Failed to exec child: " << child_pid << std::endl;
exit(-1);
} else if (child_pid < 0) {
std::cout << "Failed to fork child: " << child_pid << std::endl;
} else {
std::cout << "Child HTTP server pid: " << child_pid << std::endl;
}
}
void TearDown() {
std::cout << "Killing child pid: " << child_pid << std::endl;
kill(child_pid, SIGKILL);
}
};
TEST_F(Base, test_1) {
// http client downloading url
}
TEST_F(Base, test_2) {
// http client downloading url
}
如果您希望每个测试套件具有单个连接(单个测试夹具),则可以在夹具类中定义静态方法SetUpTestSuite()
和TearDownTestSuite()
(文档)
class Base: public ::testing::Test {
public:
static void SetUpTestSuite() {
//code here
}
static void TearDownTestSuite() {
//code here
}
};
如果您希望所有测试套件都有一个实例,则可以使用全局设置和拆卸(文档)
class MyEnvironment: public ::testing::Environment
{
public:
virtual ~MyEnvironment() = default;
// Override this to define how to set up the environment.
virtual void SetUp() {}
// Override this to define how to tear down the environment.
virtual void TearDown() {}
};
然后,您需要在GoogleTest中注册您的环境,最好是main()
(在调用RUN_ALL_TESTS
之前):
//don't use std::unique_ptr! GoogleTest takes ownership of the pointer and will clean up
MyEnvironment* env = new MyEnvironment();
::testing::AddGlobalTestEnvironment(env);
注意:代码未经过测试。
使用数据库进行测试时遇到类似的问题。 对于每次测试执行,数据库连接都已连接和断开连接。测试执行花费了太多时间,除了测试的目的是检查特定函数内的逻辑,而不是连接/断开与数据库的连接。
因此,该方法已更改为创建和使用模拟对象而不是实际对象。 也许在您的情况下,您也可以模拟服务器对象并使模拟对象返回对客户端请求的响应,并对这些响应运行断言,从而检查特定请求是否获得特定的相应响应。 因此,避免在每次测试执行时启动和停止实际服务器。
更多关于谷歌模拟在这里
更新: 如果你使用的是Visual Studio,那么你可以利用CppUnitTestFramework,它提供了在模块级别(TEST_MODULE_INITIALIZE)或类级别(TEST_CLASS_INITIALIZE)或方法级别等执行一次功能的功能。 GMock也可以与Visual Studio CppUnitTestFramework一起使用。
在此处查看 CppUnitTestFramework
- 我是否需要在下一次转移时将所有权*转移回转移队列
- 使用仅使用一次的变量调用的复制构造函数.这可能是通过调用move构造函数进行编译器优化的情况吗
- 在C++中一次将矢量值写入多个文件
- 循环中的条件:为什么每次都调用strlen(),而vector.size()只调用一次
- 为什么 zlib 放气初始化调用一次不起作用?
- 在一次迭代中从 txt 文件中读取多行
- 为什么无论你输入什么,这"while(cin.get(str,3))"只运行一次?
- 在头文件和 cpp 文件中使用一次 #pragma 时出现结构重定义错误
- 有没有办法一次声明相同类型的多个对象,并通过一个表达式立即使用相同的右值初始化它们?
- 高级选择排序 - 在一次迭代中搜索两个元素
- 具有相同特征的两个对象是否只在内存中存储一次?无论定义它们的函数是什么,都是不同的
- 如何仅使用一次固定<<设置精度(2)?或者至少恢复到默认行为?
- 谷歌基准测试,如何只调用一次代码?
- 在一次锻炼测试中发现致命信号11
- cppUnit:针对多个测试方法执行一次的设置函数
- 谷歌测试:如何为多个测试只运行一次夹具?
- 我如何检查一次测试中有多少个``期望_*`呼叫失败
- 如何在Linux中使用Makefile一次编译一堆测试C++文件
- 如何为一次只写一位的程序编写测试程序
- 是否有可能只初始化一次fixture并在多个测试用例中使用它?