Maximize Code Quality with Google Test: 4 Simple Google Test Examples to Get Started

Google Test is a Unit Test Framework provided by Google, designed for C++ and Java projects. It provides a series of tools and libraries to help developers write and execute basic unit tests, to ensure the correctness of their code.

Google Test

What is Unit Test?

Unit testing is a crucial part of the software development process, which aims to ensure that the code works as expected. The following are some of the main reasons for unit testing:

  1. Ensuring code correctness: Unit testing can ensure that the code works correctly and meets the expected requirements. This is because testing can simulate real-world usage and ensure that the code functions as expected.
  2. Discovering problems faster: When code changes, unit testing can help detect errors. This is because testing can be automatically executed, and any errors can be immediately displayed. This allows developers to identify problems earlier and resolve them more quickly.
  3. Improving code maintainability: Unit testing can improve code maintainability. This is because testing can ensure the correctness of the code and help maintenance personnel understand how the code works. This can reduce the cost of code maintenance and ensure that the code always maintains high quality.
  4. Increasing development efficiency: Unit testing can increase development efficiency. This is because it can help developers quickly identify and solve problems. In addition, unit testing can be automatically executed, so developers don’t need to manually test each function. This allows developers to focus more on developing new features without worrying about the correctness of existing code.
  5. Improving project quality: Unit testing can improve the overall quality of the project. This is because testing can ensure the correctness of the code and help detect problems more quickly. This can increase user confidence in the software and ensure that the software always maintains high quality.

Unit testing is a crucial part of the software development process because it can help ensure code correctness, improve development efficiency, improve project quality, and improve code maintainability. Typically, when we develop software, we always use unit testing to ensure that the existing test items can run properly every time we modify the program.

Google Test Examples

Google Test is an easy-to-use unit testing solution provided by Google, offering a rich set of features to assist developers in quickly writing and executing unit tests. The following are examples of practical use cases.

Checking Function Output Values

The program is an example of using Google Test to test the functionality of an addition function.

#include <gtest/gtest.h>

int add(int a, int b) {
  return a + b;
}

TEST(AdditionTest, TwoPositiveNumbers) {
  EXPECT_EQ(add(2, 3), 5);
}

TEST(AdditionTest, TwoNegativeNumbers) {
  EXPECT_EQ(add(-2, -3), -5);
}

int main(int argc, char **argv) {
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

In this example, we are testing an “add” function that takes in two integers and returns the sum of those integers.

On line 7, the TEST(AdditionTest, TwoPositiveNumbers) is a test case defined in Google Test. The TEST macro is used to define test cases in Google Test. The first parameter, AdditionTest, is the name of the test suite. The second parameter, TwoPositiveNumbers, is the name of the test case. Therefore, TEST(AdditionTest, TwoPositiveNumbers) defines a test case named “TwoPositiveNumbers” that belongs to the test suite “AdditionTest”.

This test case checks a specific part of your code and validates the test results. The name is only for convenience so that Google Test can report which tests have passed and which have failed at the end of the testing process. The naming convention is up to the user’s preference. In main(), ::testing::InitGoogleTest(&argc, argv); is used to initialize the entire test, and then RUN_ALL_TESTS is used to run all the test cases.

This code defines two tests using the TEST() macro. The first test checks if 2 + 3 equals 5, and the second test checks if (-2) + (-3) equals -5. EXPECT_EQ() is used within TEST() to indicate whether the obtained value is equal to the expected value.

Checking Array Contents

In addition to testing whether values are equal, we can also use Google Test to check if a data structure contains the expected content. For example, the following is a test for an array.

#include <gtest/gtest.h>
#include <algorithm>

int arr0[] = {};
int arr1[] = {1, 2, 3, 4, 5};

TEST(ArrayTest, EmptyArray) {
  int size = sizeof(arr0) / sizeof(arr0[0]);
  EXPECT_EQ(size, 0);
}

TEST(ArrayTest, SortedArray) {
  int size = sizeof(arr1) / sizeof(arr1[0]);
  EXPECT_TRUE(std::is_sorted(arr1, arr1 + size));
}

In this example, the tests starting from line 7 check whether an input array is an empty array. If arr0 is empty, its size should be 0. In the second test starting from line 12, we want to check whether the input array is a sorted array, so we use the std::is_sorted function from the algorithm library to check whether arr1 is sorted.

Checking the Contents of a Class Object

Google Test can also be used to test an object directly, as shown in the example below.

#include <gtest/gtest.h>
#include <string>

class Person {
 public:
  Person(std::string name, int age) : name_(name), age_(age) {}

  std::string name() const { return name_; }
  int age() const { return age_; }

 private:
  std::string name_;
  int age_;
};

TEST(PersonTest, Name) {
  Person person("John Doe", 30);
  EXPECT_EQ(person.name(), "John Doe");
}

TEST(PersonTest, Age) {
  Person person("Jane Doe", 35);
  EXPECT_EQ(person.age(), 35);
}

In this test, we have a class called Person. The test checks whether the Person object has the expected name and age. The EXPECT_EQ macro is also used here to check if they are the same.

Execution Results of Google Test

Assuming we have designed a reverseString function for reversing a string, and written three test cases as shown in the following code example.

#include <gtest/gtest.h>
#include <string>

std::string reverseString(std::string str) {
  std::reverse(str.begin(), str.end());
  return str;
}

TEST(ReverseStringTest, ReverseNormalString) {
  EXPECT_EQ(reverseString("hello"), "olleh");
}

TEST(ReverseStringTest, ReverseEmptyString) {
  EXPECT_EQ(reverseString(""), "");
}

TEST(ReverseStringTest, ReversePalindromeString) {
  EXPECT_EQ(reverseString("racecar"), "racecar");
}

int main(int argc, char **argv) {
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

When we execute this program, we will get the following output result.

[==========] Running 3 tests from 1 test case.
[----------] Global test environment set-up.
[----------] 3 tests from ReverseStringTest
[ RUN      ] ReverseStringTest.ReverseNormalString
[       OK ] ReverseStringTest.ReverseNormalString (0 ms)
[ RUN      ] ReverseStringTest.ReverseEmptyString
[       OK ] ReverseStringTest.ReverseEmptyString (0 ms)
[ RUN      ] ReverseStringTest.ReversePalindromeString
[       OK ] ReverseStringTest.ReversePalindromeString (0 ms)
[----------] 3 tests from ReverseStringTest (0 ms total)

[----------] Global test environment tear-down
[==========] 3 tests from 1 test case ran. (0 ms total)
[  PASSED  ] 3 tests.

The example shows that all three test cases of ReverseStringTest were executed and passed. Therefore, the final result shows “[PASSED] 3 tests.” If any of the test cases had failed, the developer would know which part of the code to modify.

Frequently Used Testing Macros

The following are commonly used testing macros:

  • EXPECT_EQ: used to test whether two values are equal. If the values are not equal, the test item will show as failed and the output will show the expected value and the actual value.
  • EXPECT_NE: used to test whether two values are not equal. If the values are equal, the test item will show as failed and the output will show the equal values.
  • EXPECT_TRUE: used to test whether a value is true. If the value is false, the test will fail and the output will show the false value.
  • EXPECT_FALSE: used to test whether a value is false. If the value is true, the test will fail and the output will show the true value.
  • EXPECT_STREQ: used to test whether two strings are equal. If the strings are not equal, the test item will show as failed and the output will show the expected string and the actual string.
  • EXPECT_THROW: used to test whether a statement throws an exception. If the statement does not throw an exception, the test case will fail and the output will show the statement that did not throw.
  • EXPECT_NO_THROW: used to test whether a statement does not throw an exception. If the statement throws an exception, the test case will fail and the output will show the exception that was thrown.

These are just a few examples of the testing macros in Google Test. A complete list can be found on the Google Test website.

Xponentia
Xponentia

Hello! I'm a Quantum Computing Scientist based in Silicon Valley with a strong background in software engineering. My blog is dedicated to sharing the tools and trends I come across in my research and development work, as well as fun everyday anecdotes.

Articles: 22

Leave a Reply