Test Driven Development in MVC - iFour
Tags: driven, javascript, mvc, webdev
Published: 2022-05-12 04:58:42

## 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k7bzruax9whcuk1ypocx.jpg)

## 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>

```

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](https://www.ifourtechnolab.com/blog/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>

```

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/78qozue1mlhzpbk44bb8.jpg)

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.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wcrlqviq8n3tdyu7hm77.jpg)


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>

```

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.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/580e6ch9za8993eddtrm.jpg)


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

```


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s4dwpyfzeyf6ikb4srny.jpg)


### Searching for Dedicated [ASP.NET Core Web Developer](https://www.ifourtechnolab.com/hire-asp-net-core-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>

```

And Now change in the “ShopRater” class.


```

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


```


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2cfl4hjo8waw74z11rqp.jpg)


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.