Joe Yates' Blog

Programming and DevOps

Googletest Hello World

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()

Makefile - Makefile
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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:

Hello World and Test - hello_world.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/////////////////////////////
// In the header file

#include &lt;sstream&gt;
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 &lt;gtest/gtest.h&gt;

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!