Learn creating and running MS Unit in 7 days


Figure 1:
Developer-Tester conversation.

Introduction: As the title specifies “Learn MS Unit in 7 days” I will be learning and going deep down in executing unit test and writing article for the same, the intended focus is towards beginners so that they can easily grasp the Unit testing concepts and be ready test their application before deploying QA. So let’s get started with Day 1. In case you feel I have left the very important topic feel free to comment and any corrective measures and implementation are most welcomed. I will be using VS 2015 and C# programming language as for writing the programs.

Day1 Agenda    

  1. What is a Unit Test?
  2. Benefits of Using Unit Test
  3. Testing without Unit Test
  4. Drawbacks of Manual Testing
  5. Creating Your First Unit Test
  6. Running our Unit Test?

1.1 What is a Unit Test?

Unit test is a methodology of checking that your code is working as expected by creating and running unit test. This methodology is termed as Unit Test because we break down our behavior of our program into discrete testable behaviors so that we can test each and every scenario. This discrete testable behavior can be a class or a function.

Unit Testing Framework for C#

  • MS Test
  • CSUnit
  • NUnit
  • XUnit.Net

*Note: You will thinking that we can test our application by (Manual Testing) running our application and performing the test by input the value in the page (in case of web application), sending request using postman (if it’s a API) etc. The most important benefit of Unit Testing is that we don’t need to run application in order to perform our Unit Test, we test our application isolated from the UI theres when Unit test comes into picture.

Unit test belongs to the white box testing category.

In this whole series, we will be doing Unit Testing using MS Test. MS Test is integrated with visual studio ide.

1.2 Benefits of using Unit Test:

  • Unit testing help us in finding bugs in the early stage of the Project development.
  • Unit testing make our code and function easy to understand.
  • Easier to change and test the same.
  • Provide documentation for easy understanding.

With the help of above mentioned benefits of unit testing we can create our application bug free.

1.3 Testing without Unit Test

In order to test our application we do the Manual testing. Manual testing is the process of manually testing the application for defects. It requires tester to act as end user and test all the features of the application end to end.

Simple Small Manual Testing case, In order to test your function, class you need to create a simple application. The application can be any kind of application whether it’s web, console, service, mobile etc. Unit testing is required irrespective for the type of Application. So let’s start with a simple basic console application to demonstrate Manual testing with respect of developer.

Objective: We have Class called ArithmeticOperations which performs basic Arithmetic operations, as of now we have only one operation in the class called Addition i.e. which take two number and return the result of those numbers. You have to test the ArithmeticOperations class and its respective operations.

Step1. In order to start the testing we need to create the Console Application which will be our main UI application as show below:

Figure 2:
Creating Console Application.

Step2: Once our project gets loaded, let add new class library to the solution.

Figure 3:
Adding Class Library.

Step3: Now add Class Library project and name it as Arithmetic

Figure 4:
Select Class Library.

Step 4: Once the class library is created create your Class called ArithmeticOperations and create respective properties as shown below:

namespace Arithmetic
{
 ///
 <summary>
 /// ArithmeticOperations class is responsible for performing 
 /// all Arithmetic operations
 ///
 </summary>
 public class ArithmeticOperations
 {

 public int FirstNumber { get; set; }
 public int SecondNumber { get; set; }
 public int Result { get; set; }
 ///
 <summary>
 /// Addition method performs Addition of two numbers
 ///
 </summary>
 ///
 <param name="_firstNum"></param>
 ///
 <param name="_secondNumber"></param>
 ///
 <returns>Sum of two numbers</returns>
 public int Addition(int _firstNum,int _secondNumber)
 {
 this.FirstNumber = _firstNum;
 this.SecondNumber = _secondNumber;
  return this.Result = this.FirstNumber + this.SecondNumber;
} }}

So here we have created a Simple class called ArithmeticOperations
with its properties and one method Addition which take two integers as a parameter and return the Sum of both.

Now in order to use this class library in our program we need to add reference of Arithmetic class library into our main project as shown below:


Figure 5:
Add reference of class library


Figure 6: Adding library to the Console application.

And check the checkbox Arithmetic Class library. So now we are ready to consume the namespace Arithmetic in our project.

Now in order to call the Addition method we need to Instantiate the ArithmeticOperations class and pass the required numbers as shown below:

using System;
using Arithmetic;
namespace MainProject
{
 class Program
 {
 static void Main(string[] args)
 {
 try
 {
 ArithmeticOperations arithmetic = new ArithmeticOperations();
 Console.WriteLine("Enter first number");
 arithmetic.FirstNumber = int.Parse(Console.ReadLine());
 Console.WriteLine("Enter second number");
 arithmetic.SecondNumber = int.Parse(Console.ReadLine());
  arithmetic.Result= arithmetic.Addition(arithmetic.FirstNumber, arithmetic.SecondNumber);
 Console.WriteLine($"The sum of {arithmetic.FirstNumber} and {arithmetic.SecondNumber} = {arithmetic.Result}");
 }
catch (Exception ex)
 {
 Console.WriteLine(ex.Message.ToString());
 }
 } }}

So now in order to check the sum I need to run the application and see whether the Sum of both the number is correct or not. If not then I need to run the whole application again. Let think if we have many classes and their function and we have to navigate to the desired function via UI which will take a lot of time to do, as we are doing above to check the result we are executing our application as shown below, press ctrl+F5 or F5.


Figure 7:
Output of the operation performed.

We can see the desired result and its fine as Sum of 10 and 20 is 30. What if in a hurry in Addition function we changed + to -. The whole meaning of method will change and will result in a bug.


 public int Addition(int _firstNum,int _secondNumber)
 {
 this.FirstNumber = _firstNum;
 this.SecondNumber = _secondNumber;
 return this.Result = this.FirstNumber - this.SecondNumber;
} 

Now once we run our application, we will find that 10 +20=-10 i.e. there is a bug in our application. So we will change the same to + again.


Figure 8:
Output after bug in the application.

1.4 Drawbacks of Manual Testing:

  • Time Consuming
  • If something goes wrong we need to stop our application and change the specific code and re run our application from start.
  • As it’s time consuming process we are not able to test all the scenarios.
  • Boring and lots of human intervention- No developer would like to keep filling the same forms again and again in order to test the scenario.

Now we have seen the testing application by running the whole application and testing the scenario from the UI to the desired functionality step by step. We can see the drawbacks of full loading of application and navigating to the desired UI to test the functionality, now what if I don’t want to load whole application and just want to check whether my Addition method is correct or not by passing the integer parameter from the code and specifying my expected output to the application. Here when MS Unit test comes into picture.

1.5 Creating your first Unit Test

As we have our class library Arithmetic and now in order to perform a unit test we will add a new project to the solution called Test as shown below:


Figure 9: Creating UNIT Test

Once done click ok and we are ready with our ArithmeticTest, We will see that Visual studio creates a Class UnitTest1 for us as shown below:

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace ArithmeticTest
{
 [TestClass]
 public class
 UnitTest1
 {
 [TestMethod]
 public void TestMethod1()
 {
 }
 }
}

We can also create a Unit Test just by right click on our Class method and select Create Unit Tests as shown below:


Figure 10: Other options available for Creating Unit Test.

Rename the project name or other fields as per you requirement. Code for Test Method options will provide you the default functionality like Assert.Fail() or throw
new
NotImplementedException();


Figure 11: Test Screen.

Here I will be following our Step by Step Process as we started earlier for the Unit test.

Let change the Name of our class ArithmeticTests

namespace ArithmeticTest
{
 [TestClass]
 public class ArithmeticTests
 {
 [TestMethod]
 public void TestMethod1()
 {
 }
 }
}

Now our ArithmeticTests class will contain all our test methods, in future if we add Divide, Subtraction, and Multiplication etc. We can add test cases for them as well in this class. Visual studio has placed an Attribute called TestMethod which specifies the information that this is a TestMethod, now we are given with TestMethod1 which as per of function is not meaning full so we will change the same to Test_Addition as shown below:

namespace ArithmeticTest
{
 [TestClass]
 public class ArithmeticTests
 {
 [TestMethod]
 public void Test_Addition()
 {
 }
}}

Now in order to test our ArithmeticOperations Class we need to address reference in our test project as shown below:

Figure 12: adding reference of Arithmetic Class library in our Unit test.

Enter ok and we ready to create our test for ArithmeticOperations.

Before writing our tests we need to understand AAA pattern in Unit Testing. AAA pattern stands for Arrange, Act and Assert patter.

For more information: http://c2.com/cgi/wiki?ArrangeActAssert

  • Arrange: Arrange the requirement or dependencies, properties, parameters, class initialization that are needed for the test to run. In our test we need two numbers to be passed to the Addition function.
  • Act: Invoke the code that is needed to be tested.
  • Assert: specifies the expectation from the test and if test doesn’t behaves as expected then result it into fail.

MS Test follows this pattern as it leverages us with many benefits as mentioned in above Url.

Let’s follow the AAA principle and write the code as shown below for the test:

 [TestMethod]
 public void Test_Addition()
 {
 //Arrange- Arrange the requirement
 int expectedSum = 30;
 ArithmeticOperations arithmetic = new ArithmeticOperations();
 arithmetic.FirstNumber = 10;
 arithmetic.SecondNumber = 20;
 //Act--Invoke the code that is needed to be tested
 int actualSum =arithmetic.Addition(arithmetic.FirstNumber, arithmetic.SecondNumber);
 //Assert- Expectation compared with actual result
 Assert.AreEqual(expectedSum, actualSum);
 }
 

We can see that how AAA pattern simplify our unit test code in more documented and readable manner.

Assert class has many static methods which we will discuss in our upcoming article, as of now Assert.AreEqual Verifies that specified values are equal.

1.5 Running our Unit Test

Now once we are ready with our AAA pattern we are ready to run our test, in order to run the test we can right click on testName and select Run Tests as shown below:

Figure 13: Running our First Unit Test.

As soon as we select this option vs will start running all are test present in our test project as shown below with the desired result pass or fail.

Figure 14: Result output of Unit test.

Running on the selected Test:

In order to run the selected test than go to Test menu bar and then go to window tab as shown below:

Figure 15: Running selected Unit test.

Test Explorer will open as shown below where we can select the test we want to run.

Figure 16: Test explorer window

Right Click on the test you want to run and then right click on test and select run selected test as shown below:

Figure 17: Running selected tests

The    specifies the test has passed the expectation, while if we change the expectedSum value to 20 and again run our test we can see the   failed scenario as well as shown below:

Figure 17: Showing Failed test.

Acknowledgements

We found how easy and efficient is to create a Unit test, as a practice I would suggest all developers to create unit test for best practices, in my scenario I was the developer and tester also so creating unit test cases gave me confident of my work. We have finally created our first Unit test. The test source code is uploaded to github https://github.com/SailleshPawar/MS-Unit-Test-Day1. Stay tuned for upcoming articles

One thought on “Learn creating and running MS Unit in 7 days

  1. Hi
    This is Gclowd.Pvt.Ltd
    We came to know about our team leader Gaurav Singh Tomar he told that you are a software programer. So we have created this new website named gclowd.simdif.com and we are giving a advertisement option to all the other websites. We’ll like to show your website advertisement on aur pages free of cost specially for you. Reply us if you want to get advertised in our website http://gclowd.simdif.com

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.