We need a good level of abstraction and isolation, but how
we can achieve it in our design and code? This is possible via abstract base
classes and interfaces because both these concepts provide some level of
abstraction for us.
Unit testing is tight to abstract base classes and
interfaces and there are lots of patterns and practices around these. I do not
want to step into this topic here.
When you use abstract base classes and interfaces for
abstraction then you are able to test instances of these classes easily because
they all have some main methods that you need to call and use. This is very
helpful when unit testing because it gives you much control on the classes that
play a role in your testing units.
But how does one choose between abstract base classes and
interfaces? Even though they both provide abstraction for us, each of them has
some limitations for its own.
Phil Haack, my dear friend and a member of ASP.NET MVC team
at Microsoft, has some blog posts that explain these limitations and what they
faced with usage of interfaces in first CTP of ASP.NET MVC framework that
forced them to switch to abstract base classes in the second CTP and most
likely all the future versions.
·
Versioning
Issues With Abstract Base Classes and Interfaces
·
Abstract
Base Classes Have Versioning Problems Too
·
The
Cost Of Breaking Changes
From an end user point of view, you may not care much about
such stuff though!
But finally Microsoft applied abstract base classes for
abstraction purposes in the second public release of ASP.NET MVC.
You see that these changes help you to unit test an ASP.NET
MVC application in the next sections of this article.
Microsoft has moved all these abstractions and classes to a
new assembly called System.Web.Abstractions so you
can traverse through the classes in this assembly to see what is there.
Figure 1 shows all these classes with their hierarchy and structure
which can give you some thoughts about this abstraction level.
Figure 1
As you see, here there are seven pairs of base classes and
some classes that derive from them. All these abstract base classes are
representing some traditional ASP.NET classes that had many dependencies. So
this abstraction can help the unit testing process as you will notice this
later in the next part.
But in a nutshell, we can group these classes into seven
categories:
·
HttpSessionState
·
HttpServerUtility
·
HttpContext
·
HttpResponse
·
HttpRequest
·
HttpBrowserCapabilities
·
HttpCachePolicy
As you see, all these categories are strongly tight to
server, client properties and characteristics, but this new abstraction helps
to reduce these dependencies and improve the testability.