Many junior/fresher developers might be confused about who really should deal with Unit Testing. Unit test cases are written by developers.

What is Unit Testing?

It tests the behavior of a function/method by writing another piece of code.

Unit testing

Image 1. Unit testing

Why Unit Tests?

Imagine a situation where the change requests are happening very frequently. The efforts required for regression testing will be very high and the possibility of having defects will also be high.

Software Maintenance with a Normal approach (Regression Testing)

Regression testing

Image 2. Regression Testing

Regression Testing is the process of testing changes to computer programs, in order to make sure that the older programming still works with the new changes.

Software Maintenance with Unit Testing

Unit tests

Image 3. Unit Tests

Software maintenance with TDD (Test Driven Development)

TDD

Image 4. TDD

TDD is an evolutionary approach to development. It combines test-first development where you write a test before you write just enough production code to fulfill that test; and then, refactor the code to pass the test.

Writing Unit Test cases

We have two frameworks to write Unit Test cases in C#.

We have a AAA pattern to write Unit Test cases.

AAA

Image 5. AAA

  1. Arrange all the necessary preconditions and inputs.
  2. Act on the object or method under test.
  3. Assert that the expected results have occurred.

Following are the steps to create the unit test project.

Right-click on the solution explorer click on Add and select Unit Test Project.

Test Project

Image 6. Test Project

Solution Explorer

Solution Explorer

Image7. Solution Explorer

Test Class

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using BusinessManager;
namespace UnitTestProject1
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void GetNameTest()
        {
            // Arrange
            Employee objEmployee = new Employee();
            string firstName = "Narasimha";
            string lastName = "Reddy";
            string expected = "Narasimha Reddy";
            string actual;
            // Act
            actual = objEmployee.GetName(firstName, lastName);
            // Assert
            Assert.AreEqual(expected, actual);
        }
    }
}

Employee Class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BusinessManager
{
    public class Employee
    {
        public string GetName(string firstName, string lastName)
        {
            return string.Concat(firstName, " ", lastName);
        }
    }
}

I hope this will help you to get an idea about Unit Testing.