c++unit-testinggoogletest

Unit testing with google test


I want to learn using google test framework with everyday projects, so I looked up a few tutorials, but I have no idea how to get started.

I'm using Qtcreator in Ubuntu 14.04, I downloaded gtest.zip from the google site and unzipped it, but here is where it all stoped.

This is the code i want to "gtest":

//main.cpp
#include <iostream>
#include <cstdlib>
#include "fib.h"
using namespace std;


int main(int argc, char *argv[])
{

    int n = atof(argv[1]);

    fib fibnumber;
    cout << "\nDesired number is: " << fibnumber.fibRec(n) << endl;

}

//fib.h

#ifndef FIB_H
#define FIB_H

class fib
{
public:
    int fibRec(int n);
};

#endif // FIB_H

//fib.cpp
#include "fib.h"

int fib::fibRec(int n)
{

    if(n <= 0) return 0;
    if(n == 1) return 1;
    else return(fibRec(n-1)+fibRec(n-2));

}

So where do i even begin, I want to make unit test and compile it without any plugins, but i don't know how to make use of the file I unzipped and then use it to write a unit test.


Solution

  • The google Testing framework works by building it as part of your source code. That means there is no library that you have to link to, instead you build the library when you compile your code (there is a good reason for this).

    Have a look at the official documentation: https://github.com/google/googletest/blob/main/docs/primer.md

    #Steps

    1. Try to build a test testcase for your program. I can't tell you how to do it with Qtcreator but that should be easy enough to find. Create a test that will definitely fail, like the one below.

      TEST(MyFirstTest, ThisTestShallFail) { EXPECT_EQ(1, 2); }

    2. Run this very simple test to check that it fails. If you want, change it to make it pass.

    3. Start creating your unit tests. Check for a few easy number. Check boundary conditions etc.