2

I am using CPPUNIT to do unit testing for my C++ program

For non-void functions , assuming the function add() exist

int add(int num1 , int num2)
{
  return num1+num2;
}

I could do unit testing like this

void newtestclass::add()
{
    int result = add(2,3);
    CPP_ASSERT(result == 5 ); 

}

I encounter problem when i try to do unit testing for non-void functions

void printmenu()
{
    cout<<"1) Option A"
        <<endl
        <<"2) Option B";
}

How do i do unit testing for such functions to ensure 100% code coverage

I also encounter problems doing unit testing for functions nested in other functions

void menu_select(char x)
{
    if ( x == 'a')
    {
        add();
    }
    else if ( x == 'b' )
    {
        subtract();
    }

}

void menu()
{
  char choice;
  cout<<"a) Add "
      <<endl
      <<"b) Subtract";
  cin>>choice;

  menu_select(choice);

}

How do i do unit testing for such functions to ensure 100% code coverage

Computernerd
  • 7,378
  • 18
  • 66
  • 95

1 Answers1

5

First, You may rewrite your function to avoid to call global objects (as std::cout)

void printmenu(std::ostream& stream)
{
    stream << "1) Option A" << std::endl
           << "2) Option B";
}

Now you may use printmenu(std::cout); in normal usage and you may test it via:

std::stringstream ss;

printmenu(ss);
// Check that ss.str() is what you expect.

You may have to create Mock to call your function with 'fake' object. (Write MyStream if std::stringstream didn't exist)

Second, "void function" may modify some (global) states, these states may be checked before/after the call to see if these change correctly.

Third, testing the outer function will be seen as Integration testing and not unit testing from a time.

Jarod42
  • 203,559
  • 14
  • 181
  • 302