# GTest

### Installation in Ubuntu

```bash
sudo apt install libgtest-dev
```

### Usage in CMake

```bash
# gtest
find_package(GTest REQUIRED)  # GTestConfig.cmake available
include_directories(${GTEST_INCLUDE_DIRS})

add_executable (main src/main.cpp)
target_link_libraries (main ${GTEST_BOTH_LIBRARIES})

# alternatively
include(GoogleTest) # for CMake version > 3.9
```

### Tutorial

* [GoogleTest User’s Guide](https://google.github.io/googletest/) ([CMake section](https://google.github.io/googletest/quickstart-cmake.html))
* `ASSERT_*` versions generate fatal failures when they fail, and **abort the current function**.&#x20;
* `EXPECT_*` versions generate nonfatal failures, which don’t abort the current function.
* Test results will show up when you run the GTest executable after compilation.&#x20;

```cpp
// A simple test.
TEST(TestSuiteName, TestName) {//names must be valid C++ identifiers w/o underscore
  ... test body ...
}

// Tests factorial of 0.
TEST(FactorialTest, HandlesZeroInput) {
  EXPECT_EQ(Factorial(0), 1);
}

// Tests factorial of positive numbers.
TEST(FactorialTest, HandlesPositiveInput) {
  EXPECT_EQ(Factorial(1), 1);
  EXPECT_EQ(Factorial(2), 2);
  EXPECT_EQ(Factorial(3), 6);
  EXPECT_EQ(Factorial(8), 40320);
}

// Invoking the Tests
#include <gtest/gtest.h>
int main(int argc, char** argv) {
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS(); // must not ignore the return value
}
```

### GMock

When you write a prototype or test, often it’s not feasible or wise to rely on real objects entirely. A mock object implements the same interface as a real object, but lets you specify at run time how it will be used and what it should do.

GMock has been merged into GTest project in 2019.&#x20;

* [gMock for Dummies](https://google.github.io/googletest/gmock_for_dummies.html)
* Github Repository: <https://github.com/google/googlemock>
