Unit Testing in .NET

Introduction

This article shows how to do the unit testing of your project in .Net, so to do this I will actually do some tasks like:

  1. Create a table in the database with some data.
  2. Create a "Class Library" project to get the conditional results.
  3. Create a page in the website that will get the conditional results via the Class Library and display it.
  4. Create a Unit Test project that will have:

    • Expected value like bool value
    • Actual value that will obtained by calling the Class Library method with some parameters
    • Verification of the conditions using true/false propositions like Assert.AreEqual(expeted value,actual value, message)
    • Run the test.

Step 1: In the first step, I will create a table in the database that will have records of the employee like name, salary and department.

  1. Create a table named "Employee" with some columns as in the following:

    Create table MyEmployee
    (
        ID int identity,
       
    Name varchar(20),
       
    Salary float,
       
    Department char(20)
    )
     
  2. Insert some records into the table and then the table will look like as in this command:

    select * from Employee

    table

    Note : Here 10,000 is the minimum salary and 56,000 is the maximum salary.

Step 2: In this step I will prepare a Class Library for getting the data, use the following procedure to do this.

  1. Create a new project by right-clicking on the solution file (.sln file) then seelct "Add" -> "New Project".

    Create a new project

  2. Select "Class Library" named "Class Library1" that exists in the Windows section.

    Class Library

  3. Write a method in the default class named "class1" to get the data from the database that has 2 input parameters and 1 return bool value by the expression.

    • Value: An amount of salary passed into the method that determines "Is there any salary greater than the passing salary" .
    • Strconn: Connection string
       

      public static bool GetData(string value, string strConn)

      {

          DataTable dt = new DataTable();

          string query = "select * from Employee where Salary > " + value;

          SqlConnection objConn = new SqlConnection(strConn);

          objConn.Open();

          SqlDataAdapter da = new SqlDataAdapter(query, objConn);

          da.Fill(dt);

          objConn.Close();

          return dt.Rows.Count > 0;//return bool value

      }

      Get the Data From the Database

 Step 3: In this step, I will create a website and a Default page and in this page there will be a TextBox and button. After filling in the amount of salary into the TextBox and clicking on the button, the button click event will be raised in the .cs file that will call the method of the "Class Library" project to get the bool value.

  1. Create an empty website named "website1".

    Create a empty website

  2. Create a page named "Default" in the website with a TextBox and a button.

    Create a page

    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

    <br />

    <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />

    Button OnClick Event
     

  3. Add a reference to the "Class Library" project by right-clicking on the Website1 then select "Add reference".

    Add the reference

  4. Get the result after calling the method of the Class Library and print it.
     

    protected void Button1_Click(object sender, EventArgs e)

    {

        //check the text box value is null/blank

        //check the value of text box is numeric or not

        string strConn = System.Configuration.ConfigurationManager.

        ConnectionStrings["Constr"].ConnectionString;

        bool result = ClassLibrary1.Class1.GetData(TextBox1.Text, strConn);

        Response.Write(result.ToString());

    }

    calling the method of Class Library

Run the website to check the output:

If I passed 10,000 as the amount of the salary, it returns the TRUE value, in other words a salary exists greater than the passing salary.

Run the website

If I passed 60,000 as the amount of the salary then it returns the false value, in other words there is no salary greater than the passing salary.

salary

Need of Unit Test: Suppose if I have 10 input parameters where 9 are the same and 1 is different. In the preceding scenario I need to fill in all the data again in the form for testing purposes but if I write a method in the unit test project with 10 input parameters, I can just change the single different parameter and run the test.

So back to the preceding example, now I will create a UNIT Test project.

Step 4: Create a Unit Test project named "UnitTestProject1" by right-clicking on the solution file then select "Add" -> "New Project" and select "Unit Test Project" from the "Test" section.
 
Unit Test Project 
  1. Add the reference for the Class Library project by right-clicking on the UnitTestProject1 then select "Add reference".

    reference of  Class Library

  2. Write the code to test the data where:

    • Expected value: the correct return value.
    • Actual value: call the method of "Class Library " via passing some input parameters.
    • Assert.Areequal(): Verifies the condition by comparing the expected and actual values and if both are equal then send a message.
       

      string con =""; // Connection String

      public void TestMethod1()

      {

          //Expected

          bool expected_result = true;

          //Actual

          actual_result=ClassLibrary1.Class1.GetData("10000", con);

          Assert.AreEqual(expected_result, actual_result,"Test is passed")

      }

      code
       

  3. If I run the test by right-clicking on "TestMethod" and then "Run Tests".

    TestMethod

    It automatically opens the "Test Explorer" and shows the succeeded output.

    Test Explorer

    There are some salaries in the table that are more than the input salary 10000 so the test passes.

    But if I change the input salary to 60000 and run the test then the test will fail.

    and run the test

Up Next
    Ebook Download
    View all
    Learn
    View all