Wednesday, 27 December 2017

CXXTEST introduction

Agenda:



What is unit testing in c++:


  • In General unit testing refers to testing a fundamental entity of a application. In C++ Programming unit testing refers to testing the functionality of single class without worrying about rest of the functionalities. 
  • In real time each class has dependency with other class and db/files. A good unit test should break the dependencies using mock objects, test stubs etc. 
  • Unit test helps to test our code without actual environment. Every time you make a change to existing code running the existing test suites helps us to make sure we dint break anything.

CXXTEST:

              Unit test frameworks provide a sophisticated way to write multiple cases and do assertions. CxxTest is easy to use because it does not require precompiling a CxxTest testing library, it employs no advanced features of C++ (e.g. RTTI) and it supports a very flexible form of test discovery.


Installation and Setup:

              This blog explains the installation setup for linux OS. Please install latest g++ compiler before start following this document.


Downloads

Download the cxxtest archive from here


Installation

Extract the archive in your comfortable location  /home/g/c++/cxx
Now you should see the following contents inside the extracted folder















Environment variables:

1.Set the root path of framework to $CXXTEST 







2.Update $PATH with the cxxtest bin path






WorkFlow:



Sample Test Suite:

Download the source code files here and place it in your your c++ code path.







As you can see the Calc class is the one which we are going to test. It is a simple class which just adds two numbers and return the value. 

CalcTestSuite.h

  • Include TestSuite.h header
  • Make your  CalcTestSuite class inherit from CxxTest::TestSuite.
  • Write your test cases with prefix "test".
This library provides lot of assertions like TS_ASSERT_EQUALS which compares the expected and the value returned by the target class function and returns pass / fail.

#include <cxxtest/TestSuite.h>
#include "Calc.h"

class CalcTestSuite : public CxxTest::TestSuite
{
 public:
      void testAddition(void)
      {
       Calc obj;
       TS_ASSERT_EQUALS(obj.add(3,1), 2);
      }
};

Compile and run:


1. Generate CalcTestSuite.cpp using cxxtestgen script. 

cxxtestgen -error-printer -o CalcTestSuite.cpp CalcTestSuite.h

2. Compile CalcTestSuite.cpp

 g++ -o runner -I$CXXTEST CalcTestSuite.cpp Calc.cpp 

3. Run the binary runner

 ./runner 

Test Result:

You can see the test case testAddition() expects (3+1) = 2 which obviously should fail is n't it ?







That's it you have written your First TestSuite successfully.Cheers:)

Video Demo:



No comments:

Post a Comment