我是在window下使用clion来写c++的,最近学习了gtest,中间遇到了一些问题,记录一下。
整体目录
先看一下目录结构
两个测试case,前面就有运行的标志,直接点击就能运行
具体的代码
CMakeLists.txt
cmake_minimum_required(VERSION 3.14)
project(my_project)
# GoogleTest requires at least C++11
set(CMAKE_CXX_STANDARD 11)
include(FetchContent)
FetchContent_Declare(
googletest
URL https://github.com/google/googletest/archive/609281088cfefc76f9d0ce82e1ff6c30cc3591e5.zip
)
# For Windows: Prevent overriding the parent project's compiler/linker settings
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
FetchContent_MakeAvailable(googletest)
enable_testing()
add_executable(
gtest_demo
gtest_demo_1.cc
sample1.cc
)
target_link_libraries(
gtest_demo
gtest_main
)
include(GoogleTest)
gtest_discover_tests(gtest_demo)
sample1.h
#ifndef GOOGLETEST_SAMPLES_SAMPLE1_H_
#define GOOGLETEST_SAMPLES_SAMPLE1_H_
// Returns n! (the factorial of n). For negative n, n! is defined to be 1.
int Factorial(int n);
// Returns true if and only if n is a prime number.
bool IsPrime(int n);
#endif // GOOGLETEST_SAMPLES_SAMPLE1_H_
sample1.cc
#include "sample1.h"
// Returns n! (the factorial of n). For negative n, n! is defined to be 1.
int Factorial(int n) {
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
// Returns true if and only if n is a prime number.
bool IsPrime(int n) {
// Trivial case 1: small numbers
if (n <= 1) return false;
// Trivial case 2: even numbers
if (n % 2 == 0) return n == 2;
// Now, we have that n is odd and n >= 3.
// Try to divide n by every odd number i, starting from 3
for (int i = 3; ; i += 2) {
// We only have to try i up to the square root of n
if (i > n/i) break;
// Now, we have i <= n/i < n.
// If n is divisible by i, n is not prime.
if (n % i == 0) return false;
}
// n has no integer factor in the range (1, n), and thus is prime.
return true;
}
gtest_demo_1.cc
#include <iostream>
#include <gtest/gtest.h>
#include "sample1.h"
int add(int lhs, int rhs) { return lhs + rhs; }
//int main(int argc, char* argv[]) {
// std::cout << "start gtest2222 demo \r\n" << std::endl;
// ::testing::InitGoogleTest(&argc, argv);
// return RUN_ALL_TESTS();
//}
TEST(FactorialTest, ZeroABC) {
EXPECT_EQ(2,1+1);
EXPECT_EQ(5,1+4);
}
TEST(FactorialTest, ZeroABC2) {
EXPECT_EQ(1, Factorial(0));
}
代码已经看完了,单个测试case也可以跑完了,如果我想整体运行怎么办呢?
去掉gtest_demo_1里面main方法的注释。
命令行里运行
进入项目根目录
mkdir build
cd build
cmake ..
cmake --build .
运行完上面的命令,就能看到项目结构如下:
build文件夹里面有个debug文件,再进去就能看到gtest_demo.exe
使用make命令来构建
大家记住一点在windows下,其实本身并没有make这个命令,直接使用cmake也不会产生makefile文件。
如果我就是想用make命令呢?
第一步,先在C:\Program Files\mingw64\bin里面把mingw32-make.exe复制一份,重命名为make.exe
然后回到项目根目录,删除掉build文件夹里面的所有东西。
cd build
cmake .. -G "Unix Makefiles"
make -j4
效果如下: