如何在 Xcode 12 和 macOS Big Sur 11 中运行 C/C++ 应用程序的 GTest (GoogleTest)

bla*_*cha 1 c++ macos xcode googletest

Xcode 12我已经在我的计算机上设置了一个小项目macOS Big Sur来运行我的小型数学库,但现在我想测试它是否正常工作。为此,我选择了GTest- Google 测试框架aka googletest。如果有人告诉我如何执行它,这样我就可以制作我的第一个测试套件,那就太好了?

数学.hpp

class Vector {
public:
    float x, y;
};

class Point {
public:
    float x, y;
    Point AddVector(Vector v);
};
Run Code Online (Sandbox Code Playgroud)

数学.cpp

#include "math.hpp"

Point Point::AddVector(Vector v) {
    Point p2;
    p2.x = this->x + v.x;
    p2.y = this->y + v.y;
    return p2;
};
Run Code Online (Sandbox Code Playgroud)

bla*_*cha 6

如果你想跳过无聊的事情,你可以brew install googletest

  • 确保xcode-select --install您的系统已安装(git以及clang其他好东西)
  • 安装CMake-googletest生成文件构建的方式make- 简称为构建系统
  • 从 github.com 克隆 git 存储库 -git clone https://github.com/google/googletest.git -b release-1.10.0
  • 然后:
cd googletest        # Main directory of the cloned repository.
mkdir build          # Create a directory to hold the build output.
cd build
cmake ..             # Generate native build scripts for GoogleTest.
make
sudo make install    # Install in /usr/local/ by default
Run Code Online (Sandbox Code Playgroud)
  • 您希望它在 Xcode 中工作,所以现在是访问您的项目设置的好时机。
  • 单击File > New > Target,选择Command Line Tool,将其命名为令人难忘的名称,例如MainTest,从下拉菜单中选择您的项目,并在此处选择C++语言。
  • 从左侧窗格中,选择您的项目,然后从目标中选择新创建的项目,转到build settings,然后搜索,添加带有- 库路径的header search paths新行(您甚至可以更有选择性,只添加/usr/local/include//usr/local/include/gtest
  • 在同一选项卡中,build settings搜索other linker flags并添加带有-l gtest链接器标志的行
  • 最后的 Xcode 配置步骤只是将/usr/local/lib其添加到library search paths同一个build settings选项卡中。
  • 重新访问添加路径、library search paths和的所有上述步骤header search paths,以确保它们设置为递归-否则指定库/头文件的绝对路径

在最后一步中,您应该已经正确设置了所有内容,只需编写您的test filestest-runner.

对于测试,您应该采用红绿重构原则,因此我将为您提供一个失败的测试:

//math_test.cpp
#include <gtest/gtest.h>
#include <math.h>

namespace  {
TEST(TestingTest, AddVector) {
    EXPECT_EQ(1, 2);
}
}
Run Code Online (Sandbox Code Playgroud)

最简单形式的测试运行程序应该如下所示:

//main.cpp
#include <gtest/gtest.h>

int main(int argc, const char * argv[]) {
    testing::InitGoogleTest(&argc, (char**)argv);
    return RUN_ALL_TESTS();
}
Run Code Online (Sandbox Code Playgroud)