Google Test:如何为多个测试只运行一次fixture?

spa*_*spa 5 c++ unit-testing googletest

我正在尝试使用 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
}
Run Code Online (Sandbox Code Playgroud)

Yks*_*nen 11

如果您希望每个测试套件有一个连接(单个测试夹具),那么您可以定义静态方法SetUpTestSuite()TearDownTestSuite()在您的夹具类中(文档

class Base: public ::testing::Test {
public:
    static void SetUpTestSuite() {
        //code here
    }

    static void TearDownTestSuite() {
        //code here
    }
};
Run Code Online (Sandbox Code Playgroud)

如果您希望所有测试套件都有一个实例,您可以使用全局设置和拆卸(文档

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() {}
};
Run Code Online (Sandbox Code Playgroud)

然后你需要在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);
Run Code Online (Sandbox Code Playgroud)

注意:代码未经测试。