【问题标题】:How to run gtest?如何运行gtest?
【发布时间】:2020-05-18 08:10:51
【问题描述】:

我是使用 gtest 的新手(实际上,一般是 C++) 我正在制作一个需要进行单元测试的应用程序(使用 CLion IDE,以防万一)。

我遵循的步骤:

  1. GitHub下载gtest。
  2. 将 zip 文件解压缩到我的项目中的新 lib 目录中。
  3. 修改 CMakeLists.txt

    cmake_minimum_required(VERSION 3.13)
    project(my_project)
    
    set(CMAKE_CXX_STANDARD 14)
    
    add_subdirectory(lib/gtest) # I renamed googletest-master folder to gtest, so that should be fine.
    include_directories(lib/gtest/googletest/include)
    include_directories(lib/gtest/googlemock/include)
    
    add_executable(my_project main.cpp blablabla1.h blablabla1.cpp blabla2.h blabla2.cpp etc...)
    
    target_link_libraries(my_project gtest gtest_main)
    
  4. 创建了一个名为Tests的新目录,并在其中添加了一个cpp文件,代码如下:

    #include "gtest/gtest.h"
    #include "gmock/gmock.h"
    
    TEST(TrivialTest, Negative) {
        ASSERT_EQ(0, 1);
    }
    
  5. 我被困在这里,我应该如何运行这个测试?如果我将以下代码放在main 函数中,那么每次正常运行程序时都会开始测试。我想以某种方式将运行的正常程序与运行的单元测试分开。

    #include "gtest/gtest.h"
    #include "gmock/gmock.h"
    
    int main() {
        testing::InitGoogleTest();
        return RUN_ALL_TESTS();
    }
    

【问题讨论】:

  • 我认为你误解了 C++ 中单元测试的方式。在 C++ 中,您只能运行整个可执行文件,而不是其中的一部分。这就是为什么您通常为您的应用程序提供一个可执行文件/库和一个用于单元测试的不同可执行文件。
  • @MikevanDyke 同一个项目如何生成两个exes(一个用于我的应用程序,一个用于单元测试)?
  • 您可以使用add_executable 将多个可执行文件添加到cmake 文件中,就像在this link 中所做的那样。因此,您将拥有类似add_executable(testexe testmain.cpp fileA.cpp fileB.cpp testFileA.cpp testFileB.cpp)add_executable(exe main.cpp fileA.cpp fileB.cpp) 的内容。请注意,您还需要两个不同的主文件,一个用于测试可执行文件,一个用于您的应用程序。
  • @MikevanDyke 您总是可以运行特定数量的 unitest 作为可执行文件的一部分,对吗?我的意思是使用 -gtest_filter="UnitTestClassName.*" 其中 * 也可以替换为 1 个特定测试。
  • @TsakiroglouFotis 是正确的

标签: c++ googletest


【解决方案1】:

测试源文件应该是一个单独的可执行文件,它有自己的主要功能。

您的主要源代码不应包含

    testing::InitGoogleTest();
    return RUN_ALL_TESTS();

这就是你想要的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-04
    • 2022-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-08
    • 1970-01-01
    相关资源
    最近更新 更多