In: Computer Science
Provide examples of a precondition and postcondition and discuss how they both related to unit testing.
Here is the solution,
To understand the precondition and postcondition,
lets take a sample code (function) to check a number is prime or not
void check_prime(int n)
{
int k=n/2;
for(int i = 2; i <= k; i++)
{
if(n % i == 0)
{
return 0;
}
}
return 1;
}
In the obove code, the function check_prime(n) takes a number n and then return true(1) or (false) depending upon whether the number is prime or not.
Now before passing the value 'n' to the funtion there is precondition that the number 'n' should be greater than positive and greater 1 (definition of prime number). So this becomes a precondition and it has to be check in unit testing. Imagine if we pass the value 0 to the function without checking( n> 1) then in that case the statement in the function k=n/2; would will runtime error (divide by zero).
So before passing the value to the function we have to check whether the number is greater than zero. (precondition)
Once the precondition gets checked and satisfied, the function check_prime(n) has to produce either true(1) or false(0) result. This is called as post condition.
Let us take another example:-
void deposit(int amount)
{
# balance is a global variable
balance = balance + amount;
}
Consider the above function which will deposite the amount of the customer to his/her bank account.
Now it is very important that the amount should greater than zero. Only then we have to call the function to add the amount to the customer balance. This is the pre condition.
Now once the pre condition is satisfied and after the function executes, the post condition will be that the amount should be added to the customer's account balance and should get updated.
So with these example we can clearly say the the pre condition and post condition are very much related to each other or in other words, they are interdependent on each other as well as they are relating to unit testing. So in unit testing we have to check the precondition, and when the precondition gets satisfied we have to check the post condition whether it is producing the correct output or not.
Thank You.