DEV Community

Cover image for Test Driven Development in MVC - iFour
Harshal Suthar
Harshal Suthar

Posted on • Originally published at ifourtechnolab.com

Test Driven Development in MVC - iFour

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

Image description

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<shopreviews> Reviews { get; set; }
    }
}
</shopreviews>

Enter fullscreen mode Exit fullscreen mode

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; }
    }
}

Enter fullscreen mode Exit fullscreen mode

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();
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

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


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

Enter fullscreen mode Exit fullscreen mode

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<shopreviews>();
           shop.Reviews.Add(newShopReviews()
            {
                ratings = 4
            });
         var rate = newShopRater(shop);
         var result = rate.ComputeRating(10);

         Assert.AreEqual(4, result.Rating);
        }
    }
}</shopreviews>

Enter fullscreen mode Exit fullscreen mode

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”.

Image description

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;
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

Now run the project it will pass the test.

Image description

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<shopreviews>();
            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<shopreviews>();
           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);
        }
    }
}
</shopreviews></shopreviews>

Enter fullscreen mode Exit fullscreen mode

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;
        }
    }
}


Enter fullscreen mode Exit fullscreen mode

Code 8.0 Add average method of linq in ShopeRater class

Run the project and check the result.

Image description

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;
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

Image description

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(IList<shopreviews>shopReviews);
    }
    [TestClass]
    publicclassUnitTest :IRating
    {
        publicRatingResultRateCompute(IList<shopreviews> _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;
        }
    }
}
</shopreviews></shopreviews>

Enter fullscreen mode Exit fullscreen mode

And Now change in the “ShopRater” class.


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


Enter fullscreen mode Exit fullscreen mode

Image description

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.

Top comments (0)