google test

Table of Contents

1 setup

Download google test, make and make install. Or use package manager to install gtest.

Inside your program, just insert

#include <gtest/gtest.h>
TEST(TestCaseName, TestName) {
}

compile use -pthread -lgtest

should supply a main function in ONE file:

#include <gtest/gtest.h>
int main(int argc, char** argv) {
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

2 assertion

  • ASSERT_TRUE
  • ASSERT_FALSE
  • ASSERT_EQ (expected, actual)
  • ASSERT_NE

all the assertions can be changed into EXPECTXX.

3 fixture

Code to test:

template <typename E> // E is the element type.
class Queue {
 public:
  Queue();
  void Enqueue(const E& element);
  E* Dequeue(); // Returns NULL if the queue is empty.
  size_t size() const;
  ...
};

testing code:

class QueueTest : public ::testing::Test {
 protected:
  virtual void SetUp() {
    q1_.Enqueue(1);
    q2_.Enqueue(2);
    q2_.Enqueue(3);
  }

  // virtual void TearDown() {}

  Queue<int> q0_;
  Queue<int> q1_;
  Queue<int> q2_;
};

You need to inherit from ::testing::Test.

You can setup the project in either constructor or SetUp method. The calling sequence is: constructor, setup, test, teardown, another test. The object is deleted after each test, so it is not designed for object reuse, but for code reuse.

TEST_F(QueueTest, IsEmptyInitially) {
  EXPECT_EQ(0, q0_.size());
}

You need to use TESTF, and the first argument to the macro should be the Test class name. Note that q0_ is immediately available.

4 Run A Subset of Tests

The format of a filter is a ':'-separated list of wildcard patterns (called the positive patterns) optionally followed by a '-' and another ':'-separated pattern list (called the negative patterns). A test matches the filter if and only if it matches any of the positive patterns but does not match any of the negative patterns.

In short, <pos1>:<pos2>:<pos3>-<neg1>:<neg2>.

./foo_test --gtest_filter=*
# Runs everything in test case FooTest
./foo_test --gtest_filter=FooTest.*
# Runs any test whose full name contains either "Null" or "Constructor"
./foo_test --gtest_filter=*Null*:*Constructor*
# Runs all non-death tests.
# - negativate the pattern
./foo_test --gtest_filter=-*DeathTest.*
# Runs everything in test case FooTest except FooTest.Bar
./foo_test --gtest_filter=FooTest.*-FooTest.Bar