My understanding of unit testing is you test each function as a standalone function before you integrate them in to your program.
let us take an example of a program that calculates the area of a rectangle. Here we might have a function that gets the width and length, a function that calculate the area and a function that displays the area.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
//function that gets user input for length and width
void get_dimensions (unsigned &int, unsigned &int);//function declaration
//function definition
void get_dimensions (unsigned &int length, unsigned &int width)
{
cout << "Please enter length: ";
cin >> length;
cout << "\nPlease enter width: ";
cin >> width;
}
//function call
get_dimension (length, width);
|
So you would write a simple program that just contained this function and you would compile it.
To test it you would need to verify that user was prompted to enter length and width and you would need to verify that the function stored users input for length and width.
The first test is simple, was each cout displayed on screen? If yes that test is passed.
To test that the values entered were assigned correctly you would need to check that the values were being passed back out of the function.
Your test data could be length = 10 and width = 5 (this is valid data as both values are unsigned integers)
You could also test with invalid data: length = -5 and width = -6
So your program for unit testing this function would look like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
#include <iostream>
using namespace std;
void get_dimensions (unsigned &int, unsigned &int);//function declaration
int main ()
{
unsigned int length, width;
get_dimensions (length, width);
cout << "\nLength is: " << length << endl;//this tests that value entered for length is being passed out of function
cout << "\nWidth is: " << width << endl;//this tests that value entered for width is being passed out of function
return 0;
}
//function definition
void get_dimensions (unsigned &int length, unsigned &int width)
{
cout << "Please enter length: ";
cin >> length;
cout << "\nPlease enter width: ";
cin >> width;
}
|
So your test would pass if actual results matched expected results.
You would do this for each function and make sure each function was working. Once all the functions are working you would add them to your program and test them all together.