3 . ASP.NET MVC4 Test Driven Development

About this Tutorial

Objectives

Delegates will learn to develop web applications using C# 4.0. After completing this course, delegates will be able to:

  • Use Visual Studio 2012 effectively
  • Create commercial ASP.NET Web Applications
  • Develop user interfaces using Master Pages, Site Navigation and Themes

Audience

This course has been designed primarily for programmers new to the .Net development platform. Delegates experience solely in Windows application development or earlier versions of ASP.Net will also find the content beneficial.

Prerequisites

No previous experience in ASP.NET programming is required. But any experience you do have in programming will help. Also no experience in visual studio is required. But again any experience you do have with programming development environments will be a valuable.

Download Solutions

HTML tutorial

Quick Access

List of Contents
Lab 1: TDD with ASP.NET MVC4

Overview

Estimated Time – 40 minutes

Not what you are looking? Try the next tutorial – ASP.NET MVC4 View Techniques

In this tutorial we will go into a in-depth look into the TDD (Test Driven Development) and the use of this with ASP.NET MVC4
By the end of the tutorial you should have a working application that enables the user to view multiple pages. This new feature will be added with TDD.

How about a training course? View Course Outline.

  1. The Software created by TDD should be Flexible, maintainable software that is defect-free, How?

    • Each small part of the software is tested as we go along.
    • Software designed to be tested.
  2. Code Unit is the smallest testable application part. Unit Test is a strict written contract that a code must satisfy.

    • This ensures code unit meets design.
    • Satisfies Requirements.
    • Behaves as intended.
    • Asserts conditions to be met.
  3. Characteristics of a Unit Test

    • Isolated and focused – only one thing at a time.
    • Self-contained – no need to rely on external information.
    • Fast – Otherwise why run them.
    • Repeatable – Aids regression testing.
  4. Test First, Code Later.

    • For each new feature, write a test first.
    • Define code requirements before writing code.
    • Test based on common use cases.
    • Acceptance test to test the big picture.
    • Unit test to test the implementation.
  5. Red, green, Re-factor.

    • Write a test to express how code is used and what it must do to support a new feature – This test will fail.
    • Write enough code to pass the test, no more.
    • Re-factor – Clean code to remove redundancy and improve design.
    • Re-run tests to make sure it will still pass.
    • Repeat until done.

Benefits of using TDD and unit test

  1. Ability to work in small steps.

    • Start small-scale with obvious tests.
    • Problem becomes less daunting as you write more tests.
  2. You can demonstrate progress quickly.
  3. Code without tests risks being defective.
  4. TDD guarantees high degree of test coverage – each feature has its own test.
  5. Reduce uncertainty – proof that your code works.
  6. Reduce cost of bugs.

Lab 1: TDD with ASP.NET MVC4

Lab 1: TDD with ASP.NET MVC4
  1. One of the key benefits of ASP.NET MVC is that it facilitates unit testing, allowing you to unit test your controllers and models.
    Application
  2. To start we need to Tool up, there are many testing frameworks to choose from.

    • Microsoft Test – supported directly in visual studio as seen in the previous tutorial.
    • NUnit – Widely used in industry, Download from https://nunit.org/ or install from products folder in solution.
    • Well also use a mocking framework, Download from https://code.google.com/p/moq/ or found in the products folder in the solution. This will generate a “mock” version of a class, based on an interface.
  3. To understand TDD we need to go through the process, Hence we are going to use an initial version of the FilmsRUsOnline application to implement pagination using TDD to get us there. The application can be found in the solution folder.
  4.  

  5. Unit tests are typically housed in a separate project:

    • To do this we are going to create a class library project.
    • Select the solution FilmsRUsOnline.
    • Right click and select Add new project.
    • Navigate to Visual C# on the left hand tab menu.
    • Select Class Library and call it UnitTests.

    Class libarry

  6. We now need to add the references for Moq and NUnit in are UnitTests Reference folder.

    • This can be done for NUnit once its installed, by selecting reference.
    • Right clicking reference, going to the assemblies and finding the assembly named nunit.framework.
    • For Moq you need to do as above but instead go to browse and open the dialog and search for where you saved the Moq folder and choose Moq.ddl.
    • Also add to references Domain, FilmsRUsOnline and System.Web.Mvc.
  7. Add new class to the project UnitTests called UnitTestUtils. This will contain a helper method to encapsulate an “equality assertion” and will contain a helper method to create a mock repository.

    using Domain.Repositories;
    using Domain.Entities;
    using NUnit.Framework;
    using Moq;
    namespace UnitTests
    {
     public static class UnitTestUtils
     {
      public static void AssertEqual<T>(this T value, T expected)
      {
       Assert.AreEqual(value, expected);
      }
      public static IFilmsRepository MockFilmsRepository(params Film[] films)
      {
       // Generate an implementer of IFilmsRepository at runtime using Moq.
       var mockProductsRepos = new Mock<IFilmsRepository>();
       mockProductsRepos.Setup(x => x.Films).Returns(films);
       return mockProductsRepos.Object;
      }
     }
    }
  8. View code file.
  9.  

  10. To define unit tests:

    • Define a class and annotate it with [TestFixture].
    • For each test case, write a method and annotate with [Test].
    • Try and follow the naming convention for your test cases SUTName_WhatAmITesting_ExpectedOutcome.
    • Create a class called FilmUnitTests in the UnitTests project.


    [TestFixture]
    public class FilmUnitTests
    {
     [Test]
     public void Film_RequestPage_ReturnsPageOfFilms()
     {
      // Add code here, to test whether we can view one page of films.
      // See next codebox for all code
     }

  11. In this class called FilmUnitTests use this code:

    using Domain.Repositories;
    using Domain.Entities;
    using FilmsRUsOnline.Controllers;
    using NUnit.Framework;
    namespace UnitTests
    {
     [TestFixture]
     public class FilmUnitTests
     {
      [Test]
      public void Film_RequestPage_ReturnsPageOfFilms()
      {
       // Arrange: If there are 5 films in the repository...
       IFilmsRepository repository = UnitTestUtils.MockFilmsRepository(
         new Film { Title="Airplane", Blurb="Classic spoof airline disaster movie", Genre="Comedy", RentalPrice=1.50m },
         new Film { Title="Jaws", Blurb="Shark-fest film that spooked a generation", Genre="Thriller", RentalPrice=1.99m },
         new Film { Title="Love Actually", Blurb="Feel-good family entertainment", Genre="RomCom", RentalPrice=2.99m },
         new Film { Title="Apollo 13", Blurb="Real-life space drama", Genre="Entertainment", RentalPrice=2.99m },
         new Film { Title="Dr. No", Blurb="First appearance for Bond, James Bond", Genre="Entertainment", RentalPrice=1.50m }
       );
       // Create
       var controller = new FilmsController(repository);
       controller.PageSize = 3;
       // Act: ... then when the user asks for the second page (PageSize=3)...
       var result = controller.List(2);
       // Assert: ... they'll just see the last two films.
       var displayedFilms = (IList)result.ViewData.Model;
       displayedFilms.Count.AssertEqual(2);
       displayedFilms[0].Title.AssertEqual("Apollo 13");
       displayedFilms[1].Title.AssertEqual("Dr. No");
      }
     }
    }
  12. View code file.
  13. Eroor

  14. The code has errors and won’t compile as expected. This is the idea with TDD, so now we enhance the controller so its compatible with the unit test.

    public class FilmsController : Controller
    {
     public int PageSize = 3;
     ...
     public ViewResult List(int pageNumber = 1)
     {
      return View(filmsRepository.Films);
     }
    }
  15. View code file.
  16.  

  17. To run NUnit test:

    • Run NUnit from the Windows Start Menu.
    • in NUnit GUI, Open your UNitTests.dll assembly.
    • Click run and behold the red bar.
  18. Redbar

  19. The controller must be enhanced so that it supports the notion of paging.

    public class FilmsController : Controller
    {
     public int PageSize = 3;
     ...
     public ViewResult List(int pageNumber = 1)
     {
      return View(filmsRepository.Films
         .Skip((pageNumber - 1) * PageSize)
         .Take(PageSize)
         .ToList());
     }
    }
  20. View code file.
  21.  

  22. Now run the unit tests again and behold the green bar.
  23. Greenbar

  24. You can now change the page number to view films by typing in the URL after the / “?pageNumber=1“.
  25. Working app

We will explore in the next tutorial view techniques, in which we will be able to display the films over multiple pages.

 

Well done. You have completed the tutorial in the MVC4 course. The next tutorial is

4. ASP.NET MVC4 View Techniques


Back to beginning
Copyright © 2016 TalkIT®






If you liked this post, please comment with your suggestions to help others.
If you would like to see more content like this in the future, please fill-in our quick survey.
Scroll to Top