
@Amatya Sir,
An assertion is a method that is use for unit testing of the piece of code developed during the development phase by the programmer.
When an assertion is true indicates everything is operating as expected. When false indicates it has detected an unexpected error in the code.
Let us consider the below example
namespace UtilitiesLibraryProject
{
public class Utilities
{
/// <summary>
/// Function: CheckPositiveNegativeNumber
/// Purpose: Check if a number is positive or negative. If positive return 1 else 0
/// </summary>
/// <param name="number"></param>
/// <returns></returns>
public int CheckPositiveNegativeNumber(int number)
{
if (number > 1)
return 1;
else
return 0;
}
}
}
Now let us write a unit test method for the method
CheckPositiveNegativeNumber using Microsoft.VisualStudio.TestTools.UnitTesting;
using UtilitiesLibraryProject;
namespace UnitTestProject1
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestForNegativity()
{
Utilities objUtilities = new Utilities();
int inputValue = 0;
int expected = 0;
int actual;
actual = objUtilities.CheckPositiveNegativeNumber(inputValue);
Assert.AreEqual(expected, actual);
}
}
}
In the Test Method TestForNegativity, we are passing the value as "0" as input value to the CheckPositiveNegativeNumber function and we are checking the actual value with the expected value which we have already set to "0". This test will pass the else condition of the CheckPositiveNegativeNumber method.
For the if block to pass, we can write another unit test method as under
[TestMethod]
public void TestForPositive()
{
Utilities objUtilities = new Utilities();
int inputValue = 4;
int expected = 1;
int actual;
actual = objUtilities.CheckPositiveNegativeNumber(inputValue);
Assert.AreEqual(expected, actual);
}
Assert takes in a Boolean condition as a parameter, and shows the error dialog if the condition is false.The program proceeds without any interruption if the condition is true.
Advantages
----------- a) Assertions are especially useful in large, complicated programs and in high reliability programs.
b) Helps to write better unit test cases.
c) Assertions are used to check the pre/post conditions of the contract
C# has
Debug.Assert() in the dubug mode of the code while
Trace.Assert() for release mode of the code.
You may also be interested to read about
Understanding Code Coverage (
http://www.dotnetfunda.com/articles/show/3228/understanding-code-coverage-in-visual-studio-premium-2013 ) where we have shown how Code Coverage and Unit Testing compliments each other.
Hope the answers presented here will be helpful.
Please let us know in case you need further clarification.
--
Thanks & Regards,
RNA Team
Amatya, if this helps please login to Mark As Answer. | Alert Moderator