Use CLion to create a Cmake project, use GoogleTest and GoogleMock to test the code

1. Environment preparation

  • Pay attention to the version matching. My local version is g++ 8.1.0. At the beginning, I installed the latest version 1.10.0 of GoogleTest and found that it could not be used, so I went back to download the old version.
  • g++ 8.1.0 should work with version 1.8.1 of Google Test.
    insert image description here

Github download address: , usually the first one will do.

2. Create a project in CLion

  • The project is created and the tests can be run.
    insert image description here
    insert image description here

  • Modify the CMakeLists.txt file

# CMakeLists.txt

# 本项目的Cmake配置
cmake_minimum_required(VERSION 3.16)
project(MyProject)

# 1、设置 Google Tesk 的版本号,头文件路径,链接库路径
set(GTEST_VERSION 1.10.0)
add_subdirectory(googletest)
include_directories(googletest/include)

# 2、设置 Google Mock 的路径,头文件路径,链接库路径
set(GMOCK_DIR googletest/googlemock)
include_directories(${GMOCK_DIR}/include)
link_directories(${GMOCK_DIR}/build)

# 3、将测试代码添加到可执行文件中
add_executable(MyTest main.cpp q.cc q.h)

# 4、链接 googletest 库
target_link_libraries(MyTest gtest gtest_main)

# 5、链接 Google Mock 的链接库
target_link_libraries(MyTest gmock gmock_main)


  • Then create a new googletest folder in the current directory, and unzip the downloaded compressed package into it :
    insert image description here
    insert image description here
    insert image description here

3. Write test cases

Notice the code here:

# 3、将测试代码添加到可执行文件中
add_executable(MyTest main.cpp q.cc q.h)

main.cpp, here is the test framework.

#include <gtest/gtest.h>

TEST(HelloTest, BasicAssertions) {
    
    
    EXPECT_STRNE("hello", "world");
    EXPECT_EQ(7 * 6, 42);
}

q.cc, here is the code to test

#include "add.h"
int add(int n1,int n2)
{
    
    
    return n1+n2;
}

qh, here is the function declaration of the code to test

//
// Created by gwj11 on 2023/6/25.
//

#ifndef MYPROJECT_ADD_H
#define MYPROJECT_ADD_H
int add(int n1,int n2);


#endif //MYPROJECT_ADD_H

In this way, you can return to main.cpp to run.

insert image description here

4. Complex test cases

  • A four-piece set like the one below, downloaded from github, can also be used
    insert image description here
    insert image description here
    insert image description here

  • A bad test example. You can jump to display the specific error location.
    insert image description here
    insert image description here

  • Passed example
    insert image description here

Guess you like

Origin blog.csdn.net/qq_33957603/article/details/131387116