Unit Testing in ASP.NET

What is Unit Test?

When we write a code for each module,We are not sure what could be the possible use cases of the Module. They may pass incorrect information to the module method functanality. To validate all the scenarios we need to create automated code that will check and validate the functanality.    

Why and When do we go for Unit Test?

Advantages of Unit Testing?

  1. Quality in code: With unit test cases, We can maintain quality of code in the application. Because, we suppose to modified the lines of code in the file, If this file is beeing using many places we should check all the places otherwise test case will fail. 
  2. Finding bugs easily: With unit testing, we can find bugs easily. Because, When we run the unit testing, The test case could fail. So, we can assume that the test case could fail due to some reason.  
  3. Confident in code while deploying the product: Before going to deployment we should run the unit test cases.If all the test cases is succed, We can go to deploy the product. Otherwise we can stop deoplyment and could find the issue.
  4. Reusability of code: Reusability of code is mainly helping in the unit testing
  5. Debugging easily: Unit test cases simplifies the debugging process. Before deployment the code we are running the Test cases. If there is any test case fails, It shows that the issue is in latest code.

Types of Unit Testing.

  1. NUnit
  2. xUnit
In this blog I am explaining xUnit Test Cases

What and Why is xUnit Testing?

xUnit.net is a free, open source, community-focused unit testing tool for the .NET Framework. 

xUnit.net is the latest technology for unit testing C#, VB.NET and other .NET languages. 

xUnit.net works with ReSharper, CodeRush, TestDriven.NET and Xamarin.
xUnit is a developer unit testing framework, used for buit to support test driven development. With a design goal of extreme simplicity and alignment with framework features

Creating xUnit Testing?

1. Create the MVC Application from File => New Project => Web=> ASP.NET Web Application => MVC Application

2. Create Unit Testing from File=> New Project=>Test=> xUnit Test Project


After complete creation of both MVC Application and xUnit Test applications. The project is like this.



Configuration xUnit in Unit test project


First thing, If you want to run xUnit test cases, You should install xUnit from Nuget Packages.
Ringt click on Unit Test project => Manage Nuget Packages=> search for XUnit. How to configure xUnit shown in the figure below.



2. You should install xunit.runner.visualstudio from Nuget packages. shown in the figure below

xunit.runner.visualstudio will support visual studio 2012 and higher version of xUnit.net framework. It will support .Net 2.0 and later, .Net core 1.0 and later, Universal windows app. You can see more about in this link xunit.runner.visualstudio

3.You should intstall NSubstitute in MVC Web Application from Nuget packages. shown in the below.

NSubstitute is a friendly substitute for .NET mocking frameworks. It has a simple, succinct syntax to help developers write clearer tests. NSubstitute is designed for Arrange-Act-Assert (AAA) testing and with Test Driven Development (TDD) in mind.

After all the dll's, packages installed from Nuget packages my project is shows like this. My project contains xUnit test Project and Web MVC Project



In the UnitTesting.Unit Project I have create one HomeControllerTest.cs file in the controller folder. I should write all the unit test cases related to HomeController in the UnitTesting.Web project.
In the UnitTesting.Web project i am created MVC Project. In this project HomeController.cs by default it was created from MVC Scaffolding. I am created Model users.cs file in the Models for writing user model and UserDataAccess.cs in the DataAccess Folder for writing DataAccess Business logic's.

My Model Class User.cs is this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace UnitTesting.Web.Models
{
    public class Users
    {
        public Int32 Id { get; set; }
        public string FullName { get; set; }
        public string Email { get; set; }
        public string Address { get; set; }
    }


My DataAccess class UserDataAcces.cs file is like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using UnitTesting.Web.Models;
using System.Data;
using System.Data.SqlClient;

namespace UnitTesting.Web.DataAccess
{
    public class UserDataAccess
    {
        public Users AddUser(Users user)
        {
            using (SqlConnection con = new SqlConnection("XXXXX"))
            {
                SqlCommand cmd = new SqlCommand("insert into Users(FullName, Email, Address) values('" + user.FullName + "','" + user.Email + "','" + user.Address + "'); SELECT CAST(scope_identity() AS int)", con);
                cmd.CommandType = System.Data.CommandType.Text;
                con.Open();
                Int32 id = Convert.ToInt32(cmd.ExecuteScalar());
                con.Close();
                user.Id = id;
                return user;
            }
        }
        public List<Users> GetUser()
        {
            using (SqlConnection con = new SqlConnection("XXXXX"))
            {
                SqlCommand cmd = new SqlCommand("Select Id, FullName, Email, Address from Users", con);
                cmd.CommandType System.Data.CommandType.Text;
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                da.Fill(dt);
                con.Close();
                List<Users> lst = new List<Users>();
                if (dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        var user = new Users();
                         user.Id = Convert.ToInt32(dt.Rows[i]["Id"]);
                        user.FullName = Convert.ToString(dt.Rows[i]["FullName"]);
                        user.Email = Convert.ToString(dt.Rows[i]["Email"]);
                        user.Address = Convert.ToString(dt.Rows[i]["Address"]);
                        lst.Add(user);
                    }
                }
                return lst;
            }
        }
    }

}

My Action Methods in  HomeController in UnitTesting.Web MVC Application is like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using UnitTesting.Web.DataAccess;
using UnitTesting.Web.Models;

namespace UnitTesting.Web.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        [HttpGet]
        public ActionResult AddUser()
        {
            UserDataAccess obj = new UserDataAccess();
            return View();
        }
        [HttpPost]
        public ActionResult AddUser(Users user)
        {
            UserDataAccess obj = new UserDataAccess();
            var resModel = obj.AddUser(user);
            return View();
        }
        [HttpGet]
        public ActionResult ListUser()
        {
            UserDataAccess obj = new UserDataAccess();
            var lstUsersModel = obj.GetUser();
            return View(lstUsersModel);
        }
    }

}

My Test Cases in the HomeControllerTest.cs file in UnitTesting.Unit Project is like this.

Here i wote AddUserTest() and GetUsersTest() Test cases in the HomeControllerTest.cs file

using System;
using System.Collections.Generic;
using Xunit;
using UnitTesting.Web.Controllers;
using UnitTesting.Web.Models;
using System.Web.Mvc;

namespace UnitTesting.Unit.Controller
{
    public class HomeControllerTest
    {
        [Fact]
        public void AddUserTest()
        {
            var user = new Users { FullName = "P Mahesh", Email = "maheshp@gmail.com", Address = "Hyderabad" };

            var controller = new HomeController();
            var res = controller.AddUser(user) as ViewResult;
            user = Assert.IsType<Users>(res.ViewData.Model);
            Assert.True(user.Id > 0);

        }
        [Fact]
        public void GetUsersTest()
        {
            var controller = new HomeController();
            var res = controller.ListUser() as ViewResult;
            Assert.IsType<ViewResult>(res);
            Assert.NotNull(res.ViewData.Model);
            Assert.IsType<List<Users>>(res.ViewData.Model);
        }
    }
}

In the Above test cases we are using some Assert from xUnit methods. So what are they?

Assert:  Contains various static methods that are used to verify that condition are met during the process of running test.
Assert.IsType: This will verifies that an object is exactly the given type and not a derived type.
Assert.True(): This will verifies that given expression is true or not.
Assert.NotNull(): It will verifies that Object reference should not be null

So, We can find multiple types of methods from Assert we can use based on the condition or expression.

How to run xUnit Test Cases?


1. When you wrote all the test cases. You can see all the test cases in the Test Explorer. Go To Test(Top Tool Bar)=>Windows => Test Explorer. This will open in the left side of the Visual studio. Shown in the figure.


So All the test cases are written in the HomeControllerTest.cs file those will be visible in the Test Explorer with Info icon symbol. That symbol indicates Those test cases are ready to run.

2. At the top of the Test Explorer you can find Run All button to run the Test Cases. If you click on that button it test cases will run.



If you run the test cases are run successfully the icon will changed to green color. If it fails fail message with icon will visible.

3. If you Debug or run particular Test case you also do that.


If you want to debug the particular test case Right Click on the Particular test case you can see Debug Selected Test.  You can debug the Test Case.
If you want to run particular Test Case you can see Run Selected Test. you can run the particular test case.  


Popular Posts