Posted by : Sudhir Chekuri Wednesday, 15 March 2017

Unit testing is done by the developer to check your code is working as expected or not.
It is called unit testing as the developed functionality is tested individuals as small units.
Visual Studio Test Explorer is used to find the list of unit test methods available in the project and provides options to run/debug your unit tests.
It improves the quality of the code as it is easy to test every unit of program using automated unit testing as soon as new code is added into the project.
With Test driven development by proper unit testing bugs in the code can be reduced.

You can also install add ons of other 3rd party unit testing tools in Visual Studio to use them for unit testing.


Code Example:

In the below example Unit Test project is created.
In test class(UnitTest1) two test methods are created 1. TestAuthSignInSuccess and 2. TestAuthSignInFail methods.
Original method(DUserAuth) used for user registration which has to be tested is also written in the same class.

--------------

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Data.SqlClient;
using System.Data;

namespace UTDigitalWorkSpace
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestAuthSignInSuccess()
        {
            //inputs
            string username = "ravi";
            string password = "ravi123";
            //outputs
            UnitTest1 ut = new UnitTest1();
            int result = ut.DUserAuth(username, password);

            //expected outputs
            int expectedResult = 1;
            //check
            Assert.AreEqual(result, expectedResult);
        }
        [TestMethod]
        public void TestAuthSignInFail()
        {
            //inputs
            string username = "ravi";
            string password = "ravi12344";
            //outputs
            UnitTest1 ut = new UnitTest1();
            int result = ut.DUserAuth(username, password);

            //expected outputs
            int expectedResult = 0;
            //check
            Assert.AreEqual(result, expectedResult);

        }

        public int DUserAuth(string UserName, string Password)
        {
            SqlConnection con1 = new SqlConnection(@"Data Source=.;Initial Catalog=DigitalWorkSpace;Integrated Security=True");

            SqlCommand cmd = new SqlCommand("select * from Tbl_SignUp where UserName='" + UserName + "'and password='" + Password + "'and Status='A'", con1);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);
            return ds.Tables[0].Rows.Count;
        }
    }
}


Leave a Reply

Subscribe to Posts | Subscribe to Comments

Followers

Total Pageviews

Powered by Blogger.

- Copyright © 2013 DevStudent - Metrominimalist - Powered by Blogger - Designed by Johanes Djogan -