Pesquisar

Postagens populares

segunda-feira, 15 de outubro de 2012

Installing GTest on Ubuntu, A Test Framework for C++

Nowadays, there is no talk about development without mentioning TESTS, if you develop with languages ​​like Ruby, Python, Scala ... you should already be familiar with the subject. But, what about making a Coding Dojo in C++ .
Google's framework for writing C++ tests on a variety of platforms (Linux, Mac OS X, Windows, Cygwin, Windows CE, and Symbian). Based on the xUnit architecture. Supports automatic test discovery, a rich set of assertions, user-defined assertions, death tests, fatal and non-fatal failures, value- and type-parameterized tests, various options for running the tests, and XML test report generation.

Step 1 - It's simple, just install (in Terminal):

apt-get install libgtest-dev

Now a little detail! By reason of a small rule definition of C++ language "Definition of Single Classes" the framework is not compiled at installation time, so you must compile it.

Step 2 - Find and Build (in Terminal):

# Go to your home
cd ~
# Compilling the lib
g++ -I /usr/include/gtest -I /usr/src/gtest/ -c /usr/src/gtest/src/gtest-all.cc
# Archiving the generated file to a static library
ar -rv libgtest.a gtest-all.o
# Movo to a place that the GCC Linker can find
mv libgtest.a /usr/lib/

Ok, now the framework is ready for use, see this example:

/*
Definition on Person class: Person.h
*/
#ifndef PERSON_H
#define PERSON_H

#include "string"
using std::string;

class Person{
 public:
  Person();
  void setName(string name);
  string getName();
  void setAge(int age);
  int getAge();
 private:
  string name;
  int age;
};
#endif

/*
Implementation of Person class: Person.cpp
*/

#include "Person.h"

Person::Person(){};

void Person::setName(string name){
    this->name = name;
}

string Person::getName(){
    return this->name;
}

void Person::setAge(int age){
    this->age = age;
}

int Person::getAge(){
    return this->age;
}

// Tests file: test.cpp
#include "Person.h"
#include "gtest/gtest.h"
#include "string"
using std::string;

TEST(Person, testNameMethods){
  string name = "AJ O. Alves";

  Person* person = new Person();

  person->setName(name);

  EXPECT_EQ(person->getName(), name);
}

TEST(Person, testAgeMethods){
  int age = 24;

  Person* person = new Person();

  person->setAge(age);

  EXPECT_EQ(person->getAge(), age);
}

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


To run this test is simple, there are only two considerations to be made: 
1 - If the linker can not find the GTeste, add "/usr/lib/libgtest.a" in command
2 - Always add the "-lpthread" in command


# makefile
all:
 gcc -c ./*.cpp
 g++ ./test.cpp Person.o /usr/lib/libgtest.a -o test.bin -fPIC -O2 -g -Wall -lpthread

clean:
 rm *.o
 rm ./test.bin

The output will be:

 To go deeper, visit this link and save: Documentation

Nenhum comentário: