GoogleTest 使用指南 | 通用的测试处理方式

GoogleTest 使用指南 | 通用的测试处理方式

尽管不同类型的代码需要不同的测试策略,但一些通用的方法和技术可以应用于所有测试场景,提升测试的效率和覆盖率。

使用测试夹具(Test Fixtures)

测试夹具允许在多个测试用例中共享初始化和清理代码,减少重复代码,提高测试的可维护性。

优势:

  • 代码复用:共享的设置和清理代码无需在每个测试中重复编写。
  • 组织性强:将相关的测试用例组织在一起,便于管理和理解。

示例:

#include "gtest/gtest.h"
#include <string>
#include <unordered_map>

struct Record {
    int id;
    std::string name;
};

struct Database {
    bool connect(const std::string& database_name) {
        name = database_name;
        connected = true;
        return connected;
    }

    void disconnect() {
        connected = false;
        records.clear();
    }

    bool insert(const Record& record) {
        if (!connected) {
            return false;
        }

        return records.emplace(record.id, record).second;
    }

    bool delete_record(int id) {
        if (!connected) {
            return false;
        }

        records.erase(id);
        return true;
    }

    std::string name;
    bool connected = false;
    std::unordered_map<int, Record> records;
};

class DatabaseTest : public::testing::Test {
protected:
    void SetUp() override {
        // 连接到测试数据库
        db.connect("test_db");
    }

    void TearDown() override {
        // 断开数据库连接
        db.disconnect();
    }

    Database db;
};

TEST_F(DatabaseTest, InsertRecord) {
    Record record = {1, "Test"};
    EXPECT_TRUE(db.insert(record));
}

TEST_F(DatabaseTest, DeleteRecord) {
    EXPECT_TRUE(db.delete_record(1));
}

结果:

➜  googletest-example git:(master) ✗ cmake --preset "Clang 17.0.0 arm64-apple-darwin24.6.0"
-- The C compiler identification is AppleClang 17.0.0.17000604
-- The CXX compiler identification is AppleClang 17.0.0.17000604
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working C compiler: /usr/bin/clang - skipped
-- Detecting C compile features
-- Detecting C compile features - done
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Check for working CXX compiler: /usr/bin/clang++ - skipped
-- Detecting CXX compile features
-- Detecting CXX compile features - done
CMake Warning (dev) at /opt/homebrew/share/cmake/Modules/FetchContent.cmake:1373 (message):
  The DOWNLOAD_EXTRACT_TIMESTAMP option was not given and policy CMP0135 is
  not set.  The policy's OLD behavior will be used.  When using a URL
  download, the timestamps of extracted files should preferably be that of
  the time of extraction, otherwise code that depends on the extracted
  contents might not be rebuilt if the URL changes.  The OLD behavior
  preserves the timestamps from the archive instead, but this is usually not
  what you want.  Update your project to the NEW behavior or specify the
  DOWNLOAD_EXTRACT_TIMESTAMP option with a value of true to avoid this
  robustness issue.
Call Stack (most recent call first):
  CMakeLists.txt:9 (FetchContent_Declare)
This warning is for project developers.  Use -Wno-dev to suppress it.

-- Performing Test CMAKE_HAVE_LIBC_PTHREAD
-- Performing Test CMAKE_HAVE_LIBC_PTHREAD - Success
-- Found Threads: TRUE
-- Configuring done (3.8s)
-- Generating done (0.1s)
-- Build files have been written to: /Users/xiye/CppProjects/googletest-example/out/build/Clang 17.0.0 arm64-apple-darwin24.6.0

➜  googletest-example git:(master) ✗ cmake --build "out/build/Clang 17.0.0 arm64-apple-darwin24.6.0" --target test_database
[ 16%] Building CXX object _deps/googletest-build/googletest/CMakeFiles/gtest.dir/src/gtest-all.cc.o
[ 33%] Linking CXX static library ../../../lib/libgtest.a
[ 33%] Built target gtest
[ 50%] Building CXX object _deps/googletest-build/googletest/CMakeFiles/gtest_main.dir/src/gtest_main.cc.o
[ 66%] Linking CXX static library ../../../lib/libgtest_main.a
[ 66%] Built target gtest_main
[ 83%] Building CXX object CMakeFiles/test_database.dir/test_database.cpp.o
[100%] Linking CXX executable test_database
[100%] Built target test_database

➜  googletest-example git:(master) ✗ ctest --test-dir "out/build/Clang 17.0.0 arm64-apple-darwin24.6.0" -R test_database --output-on-failure
Test project /Users/xiye/CppProjects/googletest-example/out/build/Clang 17.0.0 arm64-apple-darwin24.6.0
    Start 12: test_database
1/1 Test #12: test_database ....................   Passed    0.48 sec

100% tests passed, 0 tests failed out of 1

Total Test time (real) =   0.48 sec

参数化测试

参数化测试允许在不同参数组合下运行同一测试用例,显著提升测试覆盖率,发现更多潜在问题。

优势:

  • 高效性:一次编写,多次运行,减少重复代码。
  • 覆盖广泛:通过不同参数组合,覆盖更多的测试场景。

示例:

#include "gtest/gtest.h"

int add(int a, int b) {
    return a + b;
}

struct AddParam {
    int a;
    int b;
    int expected;
};

class AddTest : public ::testing::TestWithParam<AddParam> {
};

TEST_P(AddTest, HandlesDifferentInputs) {
    AddParam param = GetParam();

    EXPECT_EQ(add(param.a, param.b), param.expected);
}

INSTANTIATE_TEST_SUITE_P(
    AddCases,
    AddTest,
    ::testing::Values(
        AddParam{1, 2, 3},
        AddParam{0, 0, 0},
        AddParam{-1, 1, 0},
        AddParam{-2, -3, -5},
        AddParam{100, 200, 300}
    )
);

结果:

➜  googletest-example git:(master) ✗ cmake -S . -B build
CMake Warning (dev) at /opt/homebrew/share/cmake/Modules/FetchContent.cmake:1373 (message):
  The DOWNLOAD_EXTRACT_TIMESTAMP option was not given and policy CMP0135 is
  not set.  The policy's OLD behavior will be used.  When using a URL
  download, the timestamps of extracted files should preferably be that of
  the time of extraction, otherwise code that depends on the extracted
  contents might not be rebuilt if the URL changes.  The OLD behavior
  preserves the timestamps from the archive instead, but this is usually not
  what you want.  Update your project to the NEW behavior or specify the
  DOWNLOAD_EXTRACT_TIMESTAMP option with a value of true to avoid this
  robustness issue.
Call Stack (most recent call first):
  CMakeLists.txt:9 (FetchContent_Declare)
This warning is for project developers.  Use -Wno-dev to suppress it.

-- Configuring done (0.4s)
-- Generating done (0.5s)
-- Build files have been written to: /Users/xiye/CppProjects/googletest-example/build
➜  googletest-example git:(master) ✗ cmake --build build --target test_add_param
[ 33%] Built target gtest
[ 66%] Built target gtest_main
[ 83%] Building CXX object CMakeFiles/test_add_param.dir/test_add_param.cpp.o
[100%] Linking CXX executable test_add_param
[100%] Built target test_add_param
➜  googletest-example git:(master) ✗ ctest --test-dir build -R test_add_param --output-on-failure
Test project /Users/xiye/CppProjects/googletest-example/build
    Start 13: test_add_param
1/1 Test #13: test_add_param ...................   Passed    0.44 sec

100% tests passed, 0 tests failed out of 1

Total Test time (real) =   0.47 sec

Mock 对象

在复杂系统中,部分组件可能依赖外部资源或具有复杂的内部逻辑。使用 Mock 对象可以模拟这些依赖,隔离被测试单元,确保测试的独立性和可靠性。

优势:

  • 隔离性:隔离被测试单元,避免外部依赖影响测试结果。
  • 控制性:精确控制 Mock 对象的行为,模拟各种场景和异常情况。

示例:

network_interface.h:

#pragma once

#include <string>

#ifndef NETWORK_INTERFACE_H
#define NETWORK_INTERFACE_H

class NetworkInterface {
public:
    virtual ~NetworkInterface() = default;
    virtual bool send_data(const std::string& data) = 0;
};

#endif // NETWORK_INTERFACE_H

mock_network_interface.h:

#pragma once

#ifndef MOCK_NETWORK_INTERFACE_H
#define MOCK_NETWORK_INTERFACE_H

#include <gmock/gmock.h>
#include "network_interface.h"

class MockNetworkInterface : public NetworkInterface {
public:
    MOCK_METHOD(bool, send_data, (const std::string& data), (override));
};

#endif // MOCK_NETWORK_INTERFACE_H

network_client.h:

#pragma once

#ifndef NETWORK_CLIENT_H
#define NETWORK_CLIENT_H

#include <string>

#include "network_interface.h"

class NetworkClient {
public:
    explicit NetworkClient(NetworkInterface* network) : network_(network) {}

    bool send(const std::string& data) {
        if (network_ == nullptr) {
            return false;
        }

        return network_->send_data(data);
    }

private:
    NetworkInterface* network_;
};

#endif // NETWORK_CLIENT_H

test_network_client.cpp:

#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include "network_client.h"
#include "mock_network_interface.h"

using ::testing::Return;

TEST(NetworkClientTest, SendDataSuccess) {
    MockNetworkInterface mockNetwork;
    NetworkClient client(&mockNetwork);

    EXPECT_CALL(mockNetwork, send_data("Hello"))
        .WillOnce(Return(true));

    EXPECT_TRUE(client.send("Hello"));
}

TEST(NetworkClientTest, SendDataFailure) {
    MockNetworkInterface mockNetwork;
    NetworkClient client(&mockNetwork);

    EXPECT_CALL(mockNetwork, send_data("Hello"))
        .WillOnce(Return(false));

    EXPECT_FALSE(client.send("Hello"));
}

结果:

➜  googletest-example git:(master) ✗ cmake --build build --target test_network_client
[ 18%] Built target gtest
[ 45%] Built target example_lib
[ 63%] Built target gmock
[ 81%] Built target gmock_main
[100%] Built target test_network_client

➜  googletest-example git:(master) ✗ ctest --test-dir build -R test_network_client --output-on-failure
Test project /Users/xiye/CppProjects/googletest-example/build
    Start 14: test_network_client
1/1 Test #14: test_network_client ..............   Passed    0.01 sec

100% tests passed, 0 tests failed out of 1

Total Test time (real) =   0.01 sec
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

UestcXiye

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值