×
iFour Logo

Test Driven Development in MVC

iFour Team - January 01, 2021

Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

Test Driven Development in MVC

MVC is an application design model. So MVC comprised of three interconnected parts Model, View, and Controller. It is used for developing modern UI. We can create responsive websites and mobile applications using the latest version of MVC. MVC supports testability which efficiently enables TDD.

 

What is TDD?

Test-Driven Development is a software development process being converted to the test cases before the application is fully developed. The application should be in a loosely coupled manner so that we can test the independent part of the application.

Let’s start step by step testable application in MVC.


Example :
 

Step 1: - Create the project with Unit tests

Create a project
Figure 1.0 Create a project

Step 2: - Create the classes

First, create the new folder named Test. And now right-click on the folder and add classes as we described below

Here first-class is Shop, in which we have taken the list of reviews from the ShopReviews class.

 
usingSystem.Collections.Generic;
namespaceTDDwithMVC.Tests.Test
{
 publicclassShop
    {
      publicShop()
        {
        }
      public List Reviews { get; set; }
    }
}

					

The second one is ShopReviews class, which is used for shop reviews. In this class, we have one property “ratings”.

 
namespaceTDDwithMVC.Tests.Test
{
    publicclassShopReviews
    {
       publicint ratings { get; set; }
    }
}
				

In the below class, we have performed the result of ratings using the compute rating method.

 
namespaceTDDwithMVC.Tests.Test
{
publicclassShopRater
    {
private Shop data;
publicShopRater(Shop data)
        {
           this.data = data;
        }
publicRatingResultComputeRating(int rate)
        {
           return newRatingResult();
        }
    }
}
				

In the Rating Result class, there is one property which is “rating”.

 
namespaceTDDwithMVC.Tests.Test
{
publicclassRatingResult
    {
      publicRatingResult()
        {
        }
      publicint Rating { get; set; }
    }
}
				

Now create the Unit test class into the “Test” folder. Just right-click the folder and add the Unit test class. To use testing in-class use the data annotation. For class use, the data annotation “TestClass” and for method use the data annotation “TestMethod”.

 
usingMicrosoft.VisualStudio.TestTools.UnitTesting;
using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Threading.Tasks;
namespaceTDDwithMVC.Tests.Test
{
    [TestClass]
    publicclassUnitTest
    {
        [TestMethod]
        publicvoidTestMethod()
        {
           var shop = newShop();
           shop.Reviews = new List();
           shop.Reviews.Add(newShopReviews()
            {
                ratings = 4
            });
         var rate = newShopRater(shop);
         var result = rate.ComputeRating(10);
           
         Assert.AreEqual(4, result.Rating);
        }
    }
}
				

Here we have created the object of the shop class and we have added value to the ratings property. And in last, if ratings are equal then the test will be pass otherwise test will be failed.

 

Step 3: - Run the project

Now run the unit test, click on the unit test and press ctrl + R, T or directly right click and then “run test”.

Test Failure
Figure 2.0 Test Failure
 

Now replace the shop rater class with this code.

 
namespaceTDDwithMVC.Tests.Test
{
     publicclassShopRater
    {
        private Shop data;
        publicShopRater(Shop data)
        {
            this.data = data;
        }
        publicRatingResultComputeRating(int rate)
        {
            vartestResult = newRatingResult();
            testResult.Rating = 4;
            returntestResult;
        }
    }
}
					

Now run the project it will pass the test.

Test has Passed
Figure 3.0 Test has Passed
 

Now we need to write more methods to check the unit test. To check the unit test for more complex code we need to add one method which takes two reviews as below.

 
usingMicrosoft.VisualStudio.TestTools.UnitTesting;
using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Threading.Tasks;
namespaceTDDwithMVC.Tests.Test
{
    [TestClass]
    publicclassUnitTest
    {
        [TestMethod]
         publicvoidTestMethod()
        {
            var shop = newShop();
            shop.Reviews = new List();
            shop.Reviews.Add(newShopReviews()
            {
                ratings = 4
            });
            var rate = newShopRater(shop);
            var result = rate.ComputeRating(10);
            Assert.AreEqual(4, result.Rating);
        }
        [TestMethod]
        publicvoid TestMethod1()
        {
           var shop = newShop();
           shop.Reviews = new List();
           shop.Reviews.Add(newShopReviews()
            {
                ratings = 5
            });
            shop.Reviews.Add(newShopReviews()
            {
                ratings = 3
            });
           var rate = newShopRater(shop);
           var result = rate.ComputeRating(10);
 
           Assert.AreEqual(4, result.Rating);
        }
    }
}

					

And finally, add the average method in the Shop Rater class.

usingSystem.Linq;
namespaceTDDwithMVC.Tests.Test
{
    publicclassShopRater
    {
        private Shop _data;
        publicShopRater(Shop data)
        {
            this._data = data;
        }
    publicRatingResultComputeRating(int rate)
        {
            vartestResult = newRatingResult();
            testResult.Rating = (int)_data.Reviews.Average(x=>x.ratings);
            returntestResult;
        }
    }
}
					

Code 8.0 Add average method of linq in ShopeRater class

Run the project and check the result.

Unit Test
Figure 4.0 Unit Test
 

All test method has passed at minimum time. Now calculate ratings using various types of methods so we can test how much time it will take to run.

Let’s make a new method in it named “ReviewMethod”.

usingMicrosoft.VisualStudio.TestTools.UnitTesting;
using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Threading.Tasks;
namespaceTDDwithMVC.Tests.Test
{
    [TestClass]
    publicclassUnitTest
    {
        [TestMethod]
        publicvoidTestMethod()
        {
            var shop = ReviewMethod(rate: 4);
            var rate = newShopRater(shop);
            var result = rate.ComputeRating(10);
            Assert.AreEqual(4, result.Rating);
        }
    [TestMethod]
    publicvoid TestMethod1()
        {
            var shop = ReviewMethod(rate: new[]
            {
                5,
                3
            });
          var rate = newShopRater(shop);
          var result = rate.ComputeRating(10);
          Assert.AreEqual(4, result.Rating);
        }
        private Shop ReviewMethod(paramsint[] rate)
        {
           var shop = newShop();
           shop.Reviews = rate.Select(x =>newShopReviews
            {
                ratings = x
            }).ToList();
        return shop;
        }
    }
}
					
					
Unit Test
Figure 5.0 Unit Test
 

Searching for Dedicated ASP.Net Core Web Developer ? Your Search ends here.

We can see that this time is the same as the above unit test time. Now take interface “IRating” in the Unit Test class.

 
usingMicrosoft.VisualStudio.TestTools.UnitTesting;
usingSystem.Linq;
namespaceTDDwithMVC.Tests.Test
{
    publicinterfaceIRating
    {
        RatingResultRateCompute(IListshopReviews);
    }
    [TestClass]
    publicclassUnitTest :IRating
    {
        publicRatingResultRateCompute(IList _shopReviews)
        {
           varrateResult = newRatingResult();
           rateResult.Rating = (int)_shopReviews.Average(x =>x.ratings);
           returnrateResult;
        }
    [TestMethod]
    publicvoidTestMethod()
    {
         var shop = ReviewMethod(rate: 4);
         var rate = newShopRater(shop);
         var result = rate.ComputeRating(newUnitTest(), 10);
         Assert.AreEqual(4, result.Rating);
        }
    [TestMethod]
    publicvoid TestMethod1()
        {
           var shop = ReviewMethod(rate: new[]
            {
                5,
                3
            });
           var rate = newShopRater(shop);
           var result = rate.ComputeRating(newUnitTest(), 10);
           Assert.AreEqual(4, result.Rating);
        }
    private Shop ReviewMethod(paramsint[] rate)
        {
            var shop = newShop();
            shop.Reviews = rate.Select(x =>newShopReviews
            {
                ratings = x
            }).ToList();
        return shop;
        }
    }
}

					

And Now change in the “ShopRater” class.

publicRatingResultComputeRating(IRating rating, int rate)
        {
             vartestResult = _data.Reviews.Take(rate);
             returnrating.RateCompute(testResult.ToList());
        }
					
Unit Test
Figure 6.0 Unit Test
 

We can see here that method 1 takes less than 1ms time.

Conclusion

In this blog we have seen, how to perform the unit test class and measure the unit test time of class and method. Using the Test-Driven Development, we can get fast feedback. It will also reduce the time spent on rework. We spend less time in the debugger. We can identify the errors quickly and bugs will be reduced.

Test Driven Development in MVC MVC is an application design model. So MVC comprised of three interconnected parts Model, View, and Controller. It is used for developing modern UI. We can create responsive websites and mobile applications using the latest version of MVC. MVC supports testability which efficiently enables TDD.   Table of Content 1. What is TDD? 1.1.Step 1: - Create the project with Unit tests 1.2.Step 2: - Create the classes 1.3.Step 3: - Run the project 2. Conclusion What is TDD? Test-Driven Development is a software development process being converted to the test cases before the application is fully developed. The application should be in a loosely coupled manner so that we can test the independent part of the application. Let’s start step by step testable application in MVC. Example :   Step 1: - Create the project with Unit tests Figure 1.0 Create a project Step 2: - Create the classes First, create the new folder named Test. And now right-click on the folder and add classes as we described below Here first-class is Shop, in which we have taken the list of reviews from the ShopReviews class.   usingSystem.Collections.Generic; namespaceTDDwithMVC.Tests.Test { publicclassShop { publicShop() { } public List Reviews { get; set; } } } The second one is ShopReviews class, which is used for shop reviews. In this class, we have one property “ratings”.   namespaceTDDwithMVC.Tests.Test { publicclassShopReviews { publicint ratings { get; set; } } } In the below class, we have performed the result of ratings using the compute rating method.   namespaceTDDwithMVC.Tests.Test { publicclassShopRater { private Shop data; publicShopRater(Shop data) { this.data = data; } publicRatingResultComputeRating(int rate) { return newRatingResult(); } } } In the Rating Result class, there is one property which is “rating”.   namespaceTDDwithMVC.Tests.Test { publicclassRatingResult { publicRatingResult() { } publicint Rating { get; set; } } } Read More: Using Linq In MVC .NET Core Now create the Unit test class into the “Test” folder. Just right-click the folder and add the Unit test class. To use testing in-class use the data annotation. For class use, the data annotation “TestClass” and for method use the data annotation “TestMethod”.   usingMicrosoft.VisualStudio.TestTools.UnitTesting; using System; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; usingSystem.Threading.Tasks; namespaceTDDwithMVC.Tests.Test { [TestClass] publicclassUnitTest { [TestMethod] publicvoidTestMethod() { var shop = newShop(); shop.Reviews = new List(); shop.Reviews.Add(newShopReviews() { ratings = 4 }); var rate = newShopRater(shop); var result = rate.ComputeRating(10); Assert.AreEqual(4, result.Rating); } } } Here we have created the object of the shop class and we have added value to the ratings property. And in last, if ratings are equal then the test will be pass otherwise test will be failed.   Step 3: - Run the project Now run the unit test, click on the unit test and press ctrl + R, T or directly right click and then “run test”. Figure 2.0 Test Failure   Now replace the shop rater class with this code.   namespaceTDDwithMVC.Tests.Test { publicclassShopRater { private Shop data; publicShopRater(Shop data) { this.data = data; } publicRatingResultComputeRating(int rate) { vartestResult = newRatingResult(); testResult.Rating = 4; returntestResult; } } } Now run the project it will pass the test. Figure 3.0 Test has Passed   Now we need to write more methods to check the unit test. To check the unit test for more complex code we need to add one method which takes two reviews as below.   usingMicrosoft.VisualStudio.TestTools.UnitTesting; using System; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; usingSystem.Threading.Tasks; namespaceTDDwithMVC.Tests.Test { [TestClass] publicclassUnitTest { [TestMethod] publicvoidTestMethod() { var shop = newShop(); shop.Reviews = new List(); shop.Reviews.Add(newShopReviews() { ratings = 4 }); var rate = newShopRater(shop); var result = rate.ComputeRating(10); Assert.AreEqual(4, result.Rating); } [TestMethod] publicvoid TestMethod1() { var shop = newShop(); shop.Reviews = new List(); shop.Reviews.Add(newShopReviews() { ratings = 5 }); shop.Reviews.Add(newShopReviews() { ratings = 3 }); var rate = newShopRater(shop); var result = rate.ComputeRating(10); Assert.AreEqual(4, result.Rating); } } } And finally, add the average method in the Shop Rater class. usingSystem.Linq; namespaceTDDwithMVC.Tests.Test { publicclassShopRater { private Shop _data; publicShopRater(Shop data) { this._data = data; } publicRatingResultComputeRating(int rate) { vartestResult = newRatingResult(); testResult.Rating = (int)_data.Reviews.Average(x=>x.ratings); returntestResult; } } } Code 8.0 Add average method of linq in ShopeRater class Run the project and check the result. Figure 4.0 Unit Test   All test method has passed at minimum time. Now calculate ratings using various types of methods so we can test how much time it will take to run. Let’s make a new method in it named “ReviewMethod”. usingMicrosoft.VisualStudio.TestTools.UnitTesting; using System; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; usingSystem.Threading.Tasks; namespaceTDDwithMVC.Tests.Test { [TestClass] publicclassUnitTest { [TestMethod] publicvoidTestMethod() { var shop = ReviewMethod(rate: 4); var rate = newShopRater(shop); var result = rate.ComputeRating(10); Assert.AreEqual(4, result.Rating); } [TestMethod] publicvoid TestMethod1() { var shop = ReviewMethod(rate: new[] { 5, 3 }); var rate = newShopRater(shop); var result = rate.ComputeRating(10); Assert.AreEqual(4, result.Rating); } private Shop ReviewMethod(paramsint[] rate) { var shop = newShop(); shop.Reviews = rate.Select(x =>newShopReviews { ratings = x }).ToList(); return shop; } } } Figure 5.0 Unit Test   Searching for Dedicated ASP.Net Core Web Developer ? Your Search ends here. See here We can see that this time is the same as the above unit test time. Now take interface “IRating” in the Unit Test class.   usingMicrosoft.VisualStudio.TestTools.UnitTesting; usingSystem.Linq; namespaceTDDwithMVC.Tests.Test { publicinterfaceIRating { RatingResultRateCompute(IListshopReviews); } [TestClass] publicclassUnitTest :IRating { publicRatingResultRateCompute(IList _shopReviews) { varrateResult = newRatingResult(); rateResult.Rating = (int)_shopReviews.Average(x =>x.ratings); returnrateResult; } [TestMethod] publicvoidTestMethod() { var shop = ReviewMethod(rate: 4); var rate = newShopRater(shop); var result = rate.ComputeRating(newUnitTest(), 10); Assert.AreEqual(4, result.Rating); } [TestMethod] publicvoid TestMethod1() { var shop = ReviewMethod(rate: new[] { 5, 3 }); var rate = newShopRater(shop); var result = rate.ComputeRating(newUnitTest(), 10); Assert.AreEqual(4, result.Rating); } private Shop ReviewMethod(paramsint[] rate) { var shop = newShop(); shop.Reviews = rate.Select(x =>newShopReviews { ratings = x }).ToList(); return shop; } } } And Now change in the “ShopRater” class. publicRatingResultComputeRating(IRating rating, int rate) { vartestResult = _data.Reviews.Take(rate); returnrating.RateCompute(testResult.ToList()); } Figure 6.0 Unit Test   We can see here that method 1 takes less than 1ms time. Conclusion In this blog we have seen, how to perform the unit test class and measure the unit test time of class and method. Using the Test-Driven Development, we can get fast feedback. It will also reduce the time spent on rework. We spend less time in the debugger. We can identify the errors quickly and bugs will be reduced.

Categories

Ensure your sustainable growth with our team

Talk to our experts
Sustainable
Sustainable
 

Blog Our insights

 A step-by-step guide on Excel Add-in development using React.js
A step-by-step guide on Excel Add-in development using React.js

Table of Content 1.What is an Excel Add-in? 2.Prerequisites for setting up your development environment 3.How to build Excel Add-in using React 4.How to run...

Read More
11 Ways AR and VR (Augmented Reality and Virtual Reality) Transforming the Healthcare sector
11 Ways AR and VR (Augmented Reality and Virtual Reality) Transforming the Healthcare sector

Table of Content 1. Helps in surgical procedures and treats phobias 2. Create new training opportunities for doctors 3. Real-time information helps to escape from painful...

Read More
How E-discovery tools can benefit the Legal industry?
How E-discovery tools can benefit the Legal industry?

Table of Content 1.Gather essential information quickly 2.Automate and streamline tedious tasks 3.Save considerable time and money in the discovery process 4.Analyze...

Read More