googletest Hello World

Posted by Joe Yates Wed, 26 May 2010 13:17:00 GMT

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


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


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

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

compile: $(NAME).o

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

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

	gcc -c -I. -o [email protected] $<


I've put everything into a single source file 'hello-world.c++' to keep things minimal:

// In the header file

#include <sstream>
using namespace std;

class Salutation
  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"));


Just run:

  $ make


This test produces the following:

$ ./hello-world
Running main() from
[==========] 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.


It couldn't really be much simpler!