编写在预定义对象上工作的 googletests

writing googletests working on predefined object

我想为对象编写单元测试 。与普通夹具的不同之处在于,我不希望夹具在每次测试前都是 运行。夹具的 SetUp() 应该只 运行 一次,然后应该执行几个测试。在这些测试之后,应该执行夹具的 TearDown()。 我在 C++ 中使用 googletest。是否有可能实现这种行为?


清除示例:

#include "gtest/gtest.h"
class socketClientFixture : public testing::Test
{
public:
    CSocketClient *mClient;
    void SetUp()
    {
        mClient = new CSocketClient();
        mClient->connect();
    }
    void TearDown()
    {
        mClient->disconnect();
        delete mClient;
}
TEST_F(socketClientFixture, TestCommandA)
{
    EXPECT_TRUE(mClient->commandA());
}
TEST_F(socketClientFixture, TestCommandB)
{
    EXPECT_TRUE(mClient->commandA());
}
int  main(int ac, char* av[])
{
    ::testing::InitGoogleTest(&ac, av);
    int res = RUN_ALL_TESTS();
    return res;
}

在上面的示例中,我不希望在 TestCommandA 之后调用 TearDown() 并在 TestCommandB 之前调用 SetUp()。 我想要实现的行为是:

  1. 设置()
  2. 测试命令A
  3. 测试命令B
  4. 拆解()

这是因为服务器在断开连接后需要一些时间来执行一些操作。

感谢任何帮助。

没有内置方法可以满足您的要求,特别是因为您要求订购测试。

您可以在高级 google-测试文档

中从 this section 中提取更多想法

如果你愿意牺牲测试顺序,你可以完全按照上面link中给出的例子定义static void SetUpTestCase()static void TearDownTestCase()。为该 class 编写的任何测试都将参与同一装置。

Do note that if you can avoid this altogether and instantiate the connection as a Mock (see google-mock) it would be a much better alternative. This will decouple your test from the server you want to connect to so you can test your code instead of testing the server. This will also make your tests run much faster.