Unit Testing Introduction
Unit test is a procedure that instantiates a component that you have written, calls one
aspect of the functionalities of the component and checks that the component
responds correctly according to the design.
The test checks individual aspects of your code without relying on database servers,
network connections and other infrastructure.
Multiple unit tests can be performed for a single class and even for a single method in a
Unit Test Phases
Arrange the test creates an instance of the class that it will test and other required
objects to complete the test
Act the test runs the functionality that it must check
Assert the test checks the result against the expected result if the result matches what
was expected the test passes otherwise the test fail
Loosely Coupled Application
Loosely coupled application is one in which each component requires few or no details of
the other components of the system.
Loosely coupled components are essential for thorough unit testing because classes that
deal with real data, such as data from a database, can be easily be replaced with classes
that deal with test data.
Other benefits, loose coupling makes it easier to replace simple components with more
A loosely-coupled application is easy to test because you can make tests simpler by
replacing a fully functional instance of a class with a simplified instance that is specifically
designed for the test
Use Interfaces for Loosely Coupled
This creates loose coupling because you need not specify a class in code. Instead, you
can specify any implementation of a particular interface.
Loose Coupling means reducing dependencies of a class that use a different class
directly. In tight coupling, classes and objects are dependent on one another. In
general, tight coupling is usually bad because it reduces flexibility and re-usability of
code and it makes changes much more difficult and impedes testability etc.
Loose Coupling in a MVC Application
because of its separation of concerns into model, controllers, and views. Models are
simple to test because they are independent classes that you can instantiate and
configure during the arrange phase of a test. Controllers are simple classes which you
can test but it is complex to test controllers with in-memory data, rather than using a
database. To test controllers with in-memory data, you create a test double class, also
known as a fake repository.
Using Constructors to Specify a
During a unit test, call a controller constructor that takes an instance of the repository
interface as a parameter. At other times, the MVC controller factory will call the
controller constructor without any parameters.
An IoC container is a framework you can add to your application that instantiates
classes. You must configure the IoC container so that it can identify the kind of object to
create when the application expects a specific interface.
By using an IoC container, you avoid the need to create two constructors for controller
classes. During tests, you can instantiate the test double and pass it to the controller
constructor. At other times, the IoC container instantiates the actual Entity Framework
context and passes it to the controller constructor
By using a test double or mock object to supply test data, you can test your code in
isolation from other classes and from the infrastructure elements such as databases
and network connections on which the application will Rely You can create test
doubles by manually coding their instantiation, setting their properties, and populating
collections. Such test doubles are known as manual mock objects. instead of creating
mock objects manually with your own code, you can use a mocking framework to
automate this work. A mocking framework automatically creates mock object by using
the interfaces that you specify.
A mocking framework enables you to specify irrelevant properties and methods in a
given test. When the framework creates a mock object for your test, it creates stubs for
the irrelevant properties and methods. A stub is a simple implementation with little
Unit Testing for MVC controller
Tests to check the correct action result is returned from a controller action. This includes
information about the action result, such as the testing the correct view is returned for a
Test the view data returned by a controller
Tests to check if the view model is what you expected. If you have a strongly typed view
which expects class foo and you pass class bar to your view model, your code will
compile, would result in a runtime error like the one shown below. and how to test whether
or not one controller action redirects you to a second controller action
Exception & Exception Handling
an exception, which is an object that you can use to diagnose and resolve the error.
The exception contains information that you can use to diagnose the problem.
Exceptions that are not handled in your code will cause the web application to halt
and an error message to be displayed to the user.
Exception Handling in MVC
In MVC controllers, there are two methods to catch exceptions
The OnExceptionmethod is defined on the base Controllerclass, so you
can override it in any MVC controller. When you override the
OnExceptionmethod in a custom controller, MVC runs the method
whenever an exception arises and is not handled in a try/catchblock
Using the [HandleError]annotation, you can use an attribute on individual
action methods or on the controller class itself, in which case the the
[HandleError]annotation catches errors in any action. When you use the
[HandleError] annotation without properties, any exceptions are caught
and sent to an MVC
view called Error.cshtml
Custom Error Mode
To configure custom errors, add the <customErrors>element to the web.config file. This
element must be a child of the <system.web>element.
Off:Unhandled errors are displayed on the default ASP.NET error page.
On: Unhandled errors are displayed in the page you specify in the defaultRedirectattribute.
RemoteOnly: In this mode, unhandled errors are displayed differently for browsers on remote
computers and browsers on the web server. In a production site, all browsers are remote and
errors are displayed in the page that you specify in the defaultRedirectattribute. In
development situations, the developer often browses to the site on the local computer. When
an error occurs, the developer is directed to the default ASP.NET error page, which includes
debugging information such as the stack trace. Use the RemoteOnlymode on development
Logging Exception in MVC
Create a custom base controller class for your web application. This class inherits from
the System.Web.Mvc.Controllerbase class.
In your custom base controller class, override the OnException()method. Place you
error logging code in this method.
When you create controllers, inherit from your custom base controller class instead of
A route is an object that parses a requested URL, and it determines the controller and
action, to which the request must be forwarded. Such routes are called incoming
routes. HTML helpers also use routes when they formulate links to controllers and
actions. Such routes are called outgoing routes.
Routing does not operate on the protocol, server, domain, or port number of a URL but
only on the directories and file name in the relative URL
The default route examines the first three segments of the URL. Each segment is delimited
by a forward slash.
The first segment is interpreted as the name of the controller. The routing engine forwards the
request to this controller. If a first segment is not specified, the default route forwards the request
to a controller called Home.
The second segment is interpreted as the name of the action. The routing engine forwards the
request to this action. If a second segment is not specified, the default route forwards the request
to a controller called Index.
The third segment is interpreted as an ID value, which is passed to the action as a parameter. The
parameter is optional, so if a third segment is not specified, no default value is passed to the
Add Custom Routes
Every MVC web application has a Route Table object in which routes are stored, in the
Routes properties. You can add routes to the Routesproperty, by calling the
In the Visual Studio project templates for MVC 4, a dedicated RouteConfig.cscode file
exists in the App_Startfolder. This file includes the RouteConfig.RegisterRoutes()static
method, where the default route is added to the RouteTableobject. You can add
custom routes in this method. The Global.asax.csfile includes a call to
RouteConfig.RegisterRoutes() in the Application_Start()method, which means that routes
are added to the routing table whenever the MVC application starts.
Precedence of Routes
Routes are evaluated by the routing engine in the order with which they are added to
the Route Table. Routes collection. If a route matches, the routing engine uses it and
does not evaluate any later route in the collection. If a route does not match, the
routing engine ignores it and evaluates the next route in the collection. You can add
the most specific routes first
The route named "Default" matches any request, including those with no relative URL.
This default route should be the last that you add to the Route Table.Routes collection.
If the routing engine evaluates this route, the route is always used. Any routes added
after the default route are never used
A navigation structure is a logical hierarchy of webpages, which enables users to
browse to the information that interests them
Top menus. Often placed at the
top of the page or immediately
beneath the application
branding, top menus link to the
main areas of your web
Breadcrumb Trails. Often presented as a
horizontal sequence of links across the top of a
webpage, a breadcrumb trail shows the
current page and its parents in all the higher
levels of the
Tree Views. A tree view is
a hierarchical menu that
can display many items
in multiple levels in
your web application.
Footer menus. The
page footer is
often not visible
when a user arrives
on a page
MVC Site Map Provider
The MVC Site Map Provider is a provider designed to work with MVC controllers and actions.
It presents the information architecture that you can configure in a simple XML file. This
hierarchy is completely independent of the model, controllers, and actions in your
applications although you can build links to them. The provider also includes HTML helpers,
which you can use in views to render menus, tree views, and breadcrumb trails.
The MVC Site Map Provider is the only site map provider that allows you to specify a
controller and action for every item in the site map
Install it using MVCSiteMapProvider using NuGet Package
You should configure the MVC Site Map Provider, by adding elements to the web.config file
in the root folder of your MVC web application. When you install the site map provider, the
NuGet package adds a <siteMap>element to the <system.web>section of this file.
Layouts allow you to define a common style template, and then apply it to all the views in a
web application. The functionality of layouts is similar to that of the master page in a
traditional ASP.NET web application. You can use layouts to define the content layout or
logic that is shared across views.
You can define multiple layouts in an ASP.NET MVC 4 application, and each layout can have
multiple sections. You can define these sections anywhere in the layout file, even in the
<head>section of the HTML in the layout file.. Sections allow you to output dynamic content
as part of the final response.
you can build a common module or a shared view. A shared view that helps to store the
application logic is called a layout. ASP.NET MVC 4 includes features that help simplify the
process of creating and using layouts.
the @RenderBody() method
indicates to the rendering
engine where the
content of the view is placed.
The MenuBarparameter in
method specifies the name
of the section that you want
to render in the layout. The
optional; it allows you to
determine if the section you
render is required.
While developing web applications, to update individual sections in the page, you
ASP.NET MVC 4 allows partial page updates, to help update sections of a webpage,
without reloading the entire page.
Partial page updates use AJAX technologies to help update individual sections of a
webpage, during postback.
AJAX & MVC
To implement partial page updates, you need to create a view, called a partial
view, that includes only the section that you need to update.