Saturday, October 27, 2018

GTest Hello

GTest

Google test is a framework for writing C++ unit tests

Download and install

  • apt (download source code)
  • run cmake
  • copy to /usr/lib
sudo apt 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

Demo Project structure

├── CMakeLists.txt ├── bin ├── build ├── src │ ├── CMakeLists.txt │ ├── hello.cpp │ └── whattotest.cpp └── tests ├── CMakeLists.txt ├── tests.cpp └── tests_main.cpp
  • code under tests (whattotest.cpp)
#include <math.h> double squareRoot(const double a){ double b = sqrt(a); if (b != b){ return -1.0; }else { return sqrt(a); } }
  • test main file (tests_main.cpp)
#include <gtest/gtest.h> int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
  • Tests (tests.cpp)
#include "../src/whattotest.cpp" #include <gtest/gtest.h> TEST(SquareRootTest, PositiveNos) { ASSERT_EQ(6, squareRoot(36.0)); } TEST(SquareRootTest, NegativeNos) { ASSERT_EQ(-1.0, squareRoot(-15.0)); }
  • Main CMakeLists.txt
cmake_minimum_required(VERSION 3.0) project(scope) #set binary output set(EXECUTABLE_OUTPUT_PATH ${CMAKE_SOURCE_DIR}/bin) message(${EXECUTABLE_OUTPUT_PATH}) #set flags set(CMAKE_CXX_STANDARD 14) #add source directory add_subdirectory(src) add_subdirectory(tests)
  • tests folder CMakeLists.txt
# 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_main.cpp tests.cpp) target_link_libraries(runTests ${GTEST_LIBRARIES} pthread)

Reference

No comments: