I’ve already shared basics of unit testing here. Lets see some examples of unit testing. In this post, I have used MS test framework. You can use your own testing framework.
Lets take a simple example where we want to add two numbers in Calculator program and we want to test this functionality using unit test case. Here are the steps to follow:
Step 1: I’ve created console application and added calculator class with Add method as below.
Step 2: Lets add test project under same solution.
Step 3: I’ve created a class called “CalculatorTests” and decorated this class with “TestClass” attribute. This attribute is needed in order to consider all test cases as unit test cases.
Step 4: I need to add reference of earlier created console app in this test project.
Step 5: Lets add our first unit test case. Purpose of this test case will be to validate the business logic of Add() method of Calculator class.
Each test case will be decorated with “TestMethod” attribute. Each test case will be divided in to 3 parts: Arrange, Act and Assert
Arrange will have all declaration and setup related code. Act will act on our business. Assert will check whether received result is correct or not. So lets write it.
Note: Simplicity purpose, I am not adding any failing scenario here.
Now, lets add one more test case and lets see whether our business logic is able to handle that scenario or not.
In C#, we know that when we add two values and if addition of those two numbers overflows then it won’t give you an exception rather it will give you some other number. So ideally, we should thrown an exception from respective method. So here in this case, we will assert through “ExpectedException” attribute. It means that we are expecting a particular type of exception to be thrown from Add() method. See test result below.
So it means our business logic is not capable to handle overflow scenario. lets go back and update our business logic.
After running this test case,
You may have more number of test cases based on your business logic.
In upcoming blog, I will share how you can write Parameterized unit test case using MS test framework.
Happy unit testing!
2 thoughts to “Example of Unit tests using MS test framework”