googletest Hello World

2010/05/26

This is a quick run down of how to get started with using googletest on Ubuntu.

Preparation

Assuming you have a working GCC build environment, all you have to do is install the googletest packages:

$ sudo apt-get install libgtest0 libgtest-dev

Makefile

The only think of note about the Makefile is that it includes 'libgtest_main' - which implements main() and calls RUN_ALL_TESTS()

NAME = hello-world
LIBS = -lgtest_main

debug: all

run-debug:
  ./${NAME}

all: $(NAME).o
  c++ -lstdc++ $(LIBS) -o $(NAME) $(NAME).o

compile: $(NAME).o

clean:
  find . -name '*.o' -exec rm -f {} ';'
  find . -name $(NAME) -exec rm -f {} ';'

$(NAME).o: $(NAME).c++
  gcc -c -I. -o $(NAME).o $(NAME).c++

.c++.o:
  gcc -c -I. -o $@ $<

Source

I've put everything into a single source file to keep things minimal:

/////////////////////////////
// In the header file

#include 
using namespace std;

class Salutation
{
public:
  static string greet(const string& name);
};

///////////////////////////////////////
// In the class implementation file

string Salutation::greet(const string& name) {
  ostringstream s;
  s << "Hello " << name << "!";
  return s.str();
}

///////////////////////////////////////////
// In the test file
#include <gtest/gtest.h>

TEST(SalutationTest, Static) {
  EXPECT_EQ(string("Hello World!"), Salutation::greet("World"));
}

Compilation

Just run:

$ make

Output

This test produces the following:

$ ./hello-world
Running main() from gtest_main.cc
[==========] Running 1 test from 1 test case.
[----------] Global test environment set-up.
[----------] 1 test from SalutationTest
[ RUN      ] SalutationTest.Static
[       OK ] SalutationTest.Static
[----------] Global test environment tear-down
[==========] 1 test from 1 test case ran.
[  PASSED  ] 1 test.

Conclusion

It couldn't really be much simpler!