A Basic Introduction of how to write Unit Test for beginners.

Introduction

In this article you will have basic introduction of Unit Test and will learn how to write Unit Test in C#.  Writing test case is an inevitable part of software testing. Testing software is a real challenge, because there are so many types of test cases that come in so many different shapes and sizes. In order to learn how to write good Unit Test, we must first understand as to what is Unit Test and why do we need it. So lets learn that first

What do you mean by a Unit Test ?

Unit Tests simply verifies that individual units of code (mostly functions) work as expected. Usually you write the test cases yourself, but some can be automatically generated. Performing unit tests is designed to be simple, generally the tests are written in the form of functions that will determine whether a returned value equals the value you were expecting when you wrote the function. The objective in unit testing is to isolate a unit and validate its correctness. A manual approach to unit testing may employ a step-by-step instructional document.

Why do we need Unit Test ?

One of the most valuable benefits of Unit Tests is that they give you confidence that your code works as you expect it to work. Unit Tests give you the confidence to do long-term development because with unit tests in place, you know that your foundation code is dependable. Unit Tests give you the confidence to refactor your code to make it cleaner and more efficient.

There are few reasons that make you understand why a developer need to design and write out test cases to make sure major requirements of a module being validated during testing:

  • Unit testing increases confidence in changing/ maintaining code. If good unit tests are written and if they are run every time any code is changed, we will be able to promptly catch any defects introduced due to the change.
  • Unit testing finds problems early in the development cycle. This includes both bugs in the programmer’s implementation and flaws or missing parts of the specification for the unit.
  • Codes are more reusable. In order to make unit testing possible, codes need to be modular. This means that codes are easier to reuse.
  • Unit testing may reduce uncertainty in the units themselves and can be used in a bottom-up testing style approach.
  • Development is faster.
  • Codes are more reliable.
  • Easy to automate.

Lets start the show – Create your First Unit Test(Step by Step)

In this article, I would like to show that unit tests are quite easy.  Unit testing is a way for the programmer to make sure that the code that is written is fully functional and works the way it is supposed to work. Unlike the standard testing method, when a piece of code is ran an the developer or tester manually feeds the values, unit tests can test specific methods/functions (or any other code elements) by providing the test data in code.

One of the fundamental principles of unit testing is to follow TDD(Test Driven Development) where we have to write tests first, and then write the simplest code that will make the test pass. Here I am going to follow just opposite approach to make you learn how to write and Test code first. Later we will discuss TDD concept. In this article we are going to follow different approach where we will write simple code first, and then create the Unit Tests based on the possible situations. As discussed earlier, we can also write Tests first, and then write the code that will make the test pass. It depends upon individuals which one of the way to follow to test code.

Here I’ve written a basic program which can be easily understandable by any novice who’ve just started to learn C# and want to learn how to write unit test.

 public class BasicMaths
 {
 public double Add(double num1, double num2)
 {
 return num1 + num2;
 }
 public double Substract(double num1, double num2)
 {
 return num1 - num2;
 }
 public double divide(double num1, double num2)
 {
 return num1 / num2;
 }
 public double Multiply(double num1, double num2)
 {
 // To trace error while testing, writing + operator instead of * operator.
 return num1 + num2;
 }
 }

In this program, you can see that there are four basic math function Add, Substract, Divide and Multiply. All function having two double datatype parameter.

MS Unit Tests

To test above four methods, we are going to use Microsoft Testing Tools which is  MS Unit Test. To add MS unit Test follow the steps given in below image.

MSUnitTest_2

First move to Solution Explorer ( shortcut Ctrl + Alt + L to open Solution Explorer).

  • Right Click on Solution ‘Project Name’
  • Click on Add
  • Click on New Project

It will open a ‘Add New Project‘ window. Follow the given steps to create and add Unit Test Project.

MSUnitTest_3

  • Click on Test
  • Select Unit Test Project from list of available templates.
  • Write name of project. Here we are using BasicMathTest and then Click on Ok button.

It created BasicMathTest project along with BasicMath Project whose functions need to be tested. To access all four method of BasicMath in test project we need to add it reference in test project. Take a look in below image to know how to add.

MSUnitTest_4

  • Right click on Reference of MS Unit Test Project
  • Click on Add Reference

It will open a Reference Manager window. To add reference, click on Projects – Solutions – BasicMaths and click on Ok button.

You can see in below image that the reference has been added .

  • BasicMath – Having all functions which need to be tested
  • Microsoft.VisualStudio.QualityTools.UnitTestFramework – It contains all classes and methods that provide unit testing support.

MSUnitTest_10

Great, you should have something like this

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

namespace BasicMathTest
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
// TODO : Write test code
}
}
}

What will we do next is add our code to test functions of BasicMath Project.

First add namespaces

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using BasicMath;

The System namespace contains fundamental classes and base classes that define commonly-used value and reference data types, events and event handlers, interfaces, attributes, and processing exceptions.

The Microsoft.VisualStudio.TestTools.UnitTesting namespace supplies classes that provide unit testing support. This namespace contains many attributes that identify test information to the test engine regarding data sources, order of method execution, program management, agent/host information, and deployment data. The Microsoft.VisualStudio.TestTools.UnitTesting namespace also contains custom unit testing exceptions.

The BasicMath namespace contains all functions which need to be tested like Add, Substract, Multiply and Divide

Some Requirements that need to be followed

Test class requirements :

The minimum requirements for a test class are the following:

  • The [TestClass] attribute is required in the Microsoft unit testing framework for managed code for any class that contains unit test methods that you want to run in Test Explorer.
  • Each test method that you want Test Explorer to run must have the [TestMethod]attribute.

Test method requirements :

A test method must meet the following requirements:

  • The method must be decorated with the [TestMethod] attribute.
  • The method must return void.
  • The method cannot have parameters.

Writing first Unit Test method

Here, we will write Unit Test methods to verify the behavior of the Add method of the BasicMaths class. Code will look like as given below

MSUnitTest_6

In same way write test code for all method like Substract, Multiply and Divide. After adding all required test method, Our test code will look like as given below :

[TestClass]
public class UnitTest1
{

[TestMethod]
public void Test_AddMethod()
{
BasicMaths bm = new BasicMaths();
double res = bm.Add(10, 10);
Assert.AreEqual(res, 20);
}

[TestMethod]
public void Test_SubstractMethod()
{
BasicMaths bm = new BasicMaths();
double res = bm.Substract(10, 10);
Assert.AreEqual(res, 0);
}

[TestMethod]
public void Test_DivideMethod()
{
BasicMaths bm = new BasicMaths();
double res = bm.divide(10, 5);
Assert.AreEqual(res, 2);
}

[TestMethod]
public void Test_MultiplyMethod()
{
BasicMaths bm = new BasicMaths();
double res = bm.Multiply(10, 10);
Assert.AreEqual(res, 100);
}
}

We can see that in every test function We use the Microsoft unit test framework for managed code Assert.AreEqual method to verify that the ending balance is what we expect.

Build and run the test

To build and run the test.

  • Either go to Solution Explorer (Ctrl +Alt+L) and right click on Solution ‘BasicMath’ and Click on Build Solution or go to Build Menu (Alt + B) and Click on Build Solution.
  • Choose Test Menu  -> Run -> All Test. Or instead of this step you can follow given step also
  • Go to Test Explorer and Click on Run All to run tests for all test methods .

MSUnitTest_7

As the test is running the status bar at the top of the window is animated. At the end of the test run, the bar turns green if all the test methods pass, or red if any of the tests fail.
You should now see something like this :

MSUnitTest_9

In this case, If the test does fail. The test method is moved to the Failed Tests. group. Select the method in Test Explorer to view the details at the bottom of the window.

Fix your code and rerun your tests 

Analyze the test results –  The test result contains a message that describes the failure. For the AreEquals method, message displays you what was expected (the (Expected<XXX>parameter) and what was actually received (the Actual<YYY> parameter).  In this case, Message was Assert.AreEqual failed. Expected:,Actual

Correct the bug  – To correct the error, simply replace + with *.


public double Multiply(double num1, double num2)
{
return num1 * num2;
}

Rerun the Test – In Test Explorer, choose Run All to rerun the test. The red/green bar turns green, and the test is moved to the Passed Tests group.

MSUnitTest_12

Cheers! We learned how to write Unit Test.

MSUnitTestPassed1

TDD(Test Driven Development) Implementation using Unit Testing in C#

As we discussed earlier in this article that most of the developer follow write Test first then Code Later approach, we are going to learn TDD approach and how to use it.

Test-driven development (TDD) is primarily a specification technique with a side effect of ensuring that your source code is thoroughly tested at a confirmatory level.  TDD is a software development process that relies on the repetition of a very short development cycle: first the developer writes an (initially failing) automated test case that defines a desired improvement or new function, then produces the minimum amount of code to pass that test, and finally refactors the new code to acceptable standards.

MSunitesttdd1

A significant advantage of Test-driven development (TDD) is that it enables you to take small steps when writing software. As for example, Let us assume you add some new functional code, compile, and test it.  Chances are pretty good that your tests will be broken by defects that exist in the new code. It is much easier to find, and then fix, those defects if you’ve written two new lines of code than two thousand. The implication is that the faster your compiler and regression test suite, the more attractive it is to proceed in smaller and smaller steps. It is generally prefer to add a few new lines of functional code before recompile and rerun tests.

Msunittesttdd2

The motto of test-driven development is “Red, Green, Refactor.”

  • Red: Create a test and make it fail.
  • Green: Make the test pass by any means necessary.
  • Refactor: Change the code to remove duplication in your project and to improve the design while ensuring that all tests still pass.

The Red/Green/Refactor cycle is repeated very quickly for each new unit of code.

Let’s Implement TDD using MS Unit Testing

Let’s take exact same sample of code which we’ve used earlier in this article. We will create four basic function like Add, Substract, Multiply and Divide which will need to be tested. In earlier example we’ve written code first then Unit Test later but as this is TDD implementation we will write Unit Test first then will write code later.

To Write Unit Test. Follow the steps given in below image.

  • Create new project. Click on Test.
  • Click on Unit Test Project
  • Write Project name. Eg – BasicMathTDDTest and then Click on Ok button

MsUnitTest_13

you will get default code template as given below to write your test code.

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

namespace BasicMathTDDTest
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void Test_Method1()
{
// TODO : Add test logic here
}
}
}

Here we are going to write test code first before writing actual code which need to be tested.

MsUnitTest_14

Code will look like as given below


  public class UnitTest1
    {
        [TestMethod]
        public void Test_AddMethod()
        {
            BasicMaths bm = new BasicMaths();
            double res = bm.Add(20.50, 20.50);
            Assert.AreEqual(41, res);
        }

        [TestMethod]
        public void Test_MultiplyMethod()
        {
            BasicMaths bm = new BasicMaths();
            double res = bm.Multiply(10, 10);
            Assert.AreEqual(100, res);
        }
    }

As you can see that there are two test method Test_AddMethod and Test_MultiplyMethod and both method is using BasicMaths class, Add and Multiply method which is not yet defined. When we run this application you will get error as given below :

MsUnitTest_15

To make MS Unit Test run, we need to create BasicMaths class and add reference to Unit Test project. Follow given steps to know how to create BasicMaths class and adding reference to MS Unit Test Project.

  • Right click on Solution ‘BasicMathTDDTest’
  • Click on ADD
  • Click on New Project

MsunitTest_16

It will open a Add New Project window where you have to follow given steps

  • Click on Visual C# ( If you are writing code in C# language )
  • Click on Console Application
  • Write Name of Project, Here Project Name is BasicMath  and click on OK button

MsUnitTest_17

Now write Add and Multiply Method under BasicMaths class for which we have already written MS Unit Test. Code will look like as given below


public class BasicMaths
{
public double Add(double num1, double num2)
{
return num1 + num2;
}

public double Multiply(double num1, double num2)
{
return num1 + num2;
}

MsUnitTest_18

After writing code you can see that there is 0 references of BasicMaths class as well as Add method function but these function is already being used in MS Unit Test project. To make it accessible we need to add this project to MS Unit Test Project reference.

Once you add reference, Its time to run Test. To run Test you can either go to Test -> Run -> All Test or move to Test Explorer and click on Run All.  After running Tests you will see output as given below

MsUnitTest_19

Both Test Method Test_AddMethod and Test_MultiplyMethod is failed. To Know why These method failed while Testing click on each Method and read the reason.

In Test_AddMethod Assert.AreEqual  is supposed to give 41 as actual value but we are expecting 21. It must be 41 to get Test passed. Ofcourse after adding 20.50 and 20.50 we will get 41. So We have written wrong expected value. Change it to 41 instead of 21.

MsUnitTest_20

In Test_MultiplyMethod Assert.AreEqual is supposed to give 20 but we are expecting 100. It must be 20 to get test passed. But Logically after multiplying 10 and 10 we should get 100 then why its actual value is returning 20. Check code of Multiply Method in BasicMaths class.

MsUniTest_21

As we can see that we are using +(Plus) operator between two operand num1 and num2 which should be *(Multiply) operator. Now given code is logically correct one.

  public double Multiply(double num1, double num2)
        {
            return num1 * num2;
        }

MsUnitTest_22

After correcting wrongs values and codes. Lets run Test again and see the result. Both Test method Test_AddMethod and Test_MultiplyMethod is passed.

Download Source Code :  Click Me to Download

Last Words 

I hope this article will help you to learn basics of Unit Test and how to create Unit Test cases for your code in C#.  Your all suggestions are most welcome and appreciated.

Advertisements

About Ravi Ranjan Kumar

An Indian who Living, Loving & Learning Technology with different tastes and willing to share knowledge and thoughts.
This entry was posted in .Net, C#, Uncategorized and tagged , , . Bookmark the permalink.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s