GoogleTest - 运行第一个测试



在本教程中,我们将通过一个示例学习如何使用 GoogleTest 测试 C++ 代码。我们将学习运行基本测试所需的所有步骤、命令和方法。

running test on googletest

创建基本测试

按照以下步骤在 GoogleTest 中为 C++ 函数创建基本测试:

步骤 1

首先,创建一个文件夹或目录来保存您的项目。在系统的命令提示符中输入以下命令来创建文件夹:

mkdir test1

这里,我们使用文件夹名称为“test1”

步骤 2

创建一个“test_case.cc”文件,其中将包含 C++ 函数及其单元测试。您可以随意命名。

// header of the GoogleTest
#include <gtest/gtest.h>

// function for which we write unit tests
int add(int num1, int num2) {
    return num1 + num2;
}

// to test addition of positive numbers
TEST(SumTest, ForPositiveNumbers) {
    EXPECT_EQ(35, add(23, 12));
}

// to test addition of negative numbers
TEST(SumTest, ForNegativeNumbers) {
    EXPECT_EQ(-1, add(-1, 0));
}

// to test addition of positive and negative numbers
TEST(SumTest, ForMixedNumbers) {
    EXPECT_EQ(0, add(-1, 1));
}

// main() function to run all tests
int main(int argc, char **argv) {
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}

在上面的代码中,第一个单元测试检查给定的 C++ 函数是否能够正确处理两个正数。第二个测试检查add()函数是否正确地添加负数和零。最后一个单元测试检查 add() 函数是否正确地将负数和正数相加。最后,main()函数初始化 Google Test 并运行所有测试用例。

创建“CMakeLists.txt”文件

如前一章所述,每个 GoogleTest 项目都需要“CMakeLists.txt”文件。在这个文件中,我们通过使用其 github 链接来声明对 GoogleTest 的依赖,如下所示:

cmake_minimum_required(VERSION 3.14)
project(test1)

# GoogleTest requires at least C++14
set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

include(FetchContent)
FetchContent_Declare(
  googletest
  URL https://github.com/google/googletest/archive/03597a01ee50ed33e9dfd640b249b4be3799d395.zip
)
# For Windows: Prevent overriding the parent project's compiler/linker settings
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
FetchContent_MakeAvailable(googletest)

# to enable test
enable_testing()

# defining executable target and its source file
add_executable(
  test_case
  test_case.cc
)
# to link the executable with GoogleTest main library
target_link_libraries(
  test_case
  GTest::gtest_main
)

# to include GoogleTest module
include(GoogleTest)

# to discover and register all tests in the executable
gtest_discover_tests(test_case)

构建和运行测试

要构建和运行测试,请按照以下步骤操作:

步骤 1

使用以下命令导航到项目文件夹:

cd test1

步骤 2

然后,使用以下命令生成构建文件:

cmake -S . -B build

-S 指定源目录,为"."-B 指定构建目录,名为"build"

步骤 3

现在,使用上一步 CMake 生成的构建文件来编译和构建项目:

cmake --build build

步骤 4

移动到构建目录:

cd build

步骤 5

最后,使用给定的命令运行所有测试:

ctest

上述命令运行在“CMakeLists.txt”文件中使用enable_testing()命令定义的测试。

输出

控制台上的输出将如下所示:

Test project D:/gTest/test1/build
    Start 1: SumTest.ForPositiveNumbers
1/3 Test #1: SumTest.ForPositiveNumbers .......   Passed    0.02 sec
    Start 2: SumTest.ForNegativeNumbers
2/3 Test #2: SumTest.ForNegativeNumbers .......   Passed    0.01 sec
    Start 3: SumTest.ForMixedNumbers
3/3 Test #3: SumTest.ForMixedNumbers ..........   Passed    0.01 sec

100% tests passed, 0 tests failed out of 3

Total Test time (real) =   0.13 sec

您可以在LastTest.log文件中检查每个测试的结果。此文件位于:/build/Testing/Temporary。

广告
© . All rights reserved.