GTest代码测试在ubuntu其实有一个最简单的办法,不需要下载源码那么麻烦:
sudo apt-get install libgtest-dev
cd /usr/src/gtest
sudo cmake CMakeLists.txt
sudo make
# copy or symlink libgtest.a and libgtest_main.a to your /usr/lib folder
sudo cp *.a /usr/lib
上面的步骤里要注意两点,一个是你自己的lib库的地址,有可能不是在/usr/lib,而是在/usr/local/lib下,另外一个就是libgtest.a 和 libgtest_main.a可能不在/usr/src/gtest 的根目录下,而是在里面的lib目录下
然后就可以快乐调试了,测试代码如下所示:
// whattotest.cpp
#include <math.h>
double squareRoot(const double a) {
double b = sqrt(a);
if(b != b) { // nan check
return -1.0;
}else{
return sqrt(a);
}
}
// tests.cpp
#include "whattotest.cpp"
#include <gtest/gtest.h>
TEST(SquareRootTest, PositiveNos) {
ASSERT_EQ(6, squareRoot(36.0));
ASSERT_EQ(18.0, squareRoot(324.0));
ASSERT_EQ(25.4, squareRoot(645.16));
ASSERT_EQ(0, squareRoot(0.0));
}
TEST(SquareRootTest, NegativeNos) {
ASSERT_EQ(-1.0, squareRoot(-15.0));
ASSERT_EQ(-1.0, squareRoot(-0.2));
}
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
上面两个是代码文件,还有一个cmake的编译文件:
cmake_minimum_required(VERSION 2.6)
# Locate GTest
find_package(GTest REQUIRED)
include_directories(${GTEST_INCLUDE_DIRS})
# Link runTests with what we want to test and the GTest and pthread library
add_executable(runTests tests.cpp)
target_link_libraries(runTests ${GTEST_LIBRARIES} pthread)
编译和运行:
cmake CMakeLists.txt
make
./runTests
下载源码链接: https://github.com/smistad/GTest
参考文献:
Google Mock(Gmock)简单使用和源码分析——简单使用
https://blog.csdn.net/breaksoftware/article/details/51384083