As a follow-up to my previous post ASP.NET 3.5: improving testability with System.Web.Abstractions, I would like to show how the same testability can be achieved without using any mock framework like Rhino.Mocks. The C# 3.0 featuires ‘object initializers’ and ‘automatic properties’ makes our code sufficiently non-verbose to make it easy and readable.
So, given the same examples as in my previous post, here is what the test code will look like:
Example #1: Testing a page codebehind file
[TestMethod]
public void ShouldSetNoCacheabilityOnDefaultPage()
{
_Default page = new _Default();
HttpCachePolicyMock httpCachePolicyMock = new HttpCachePolicyMock();
page.SetCacheablityOfResponse(new HttpResponseStub
{
TheCache = httpCachePolicyMock
});
httpCachePolicyMock.ShouldHaveSetCacheabilityTo(HttpCacheability.NoCache);
}
class HttpResponseStub : HttpResponseBase
{
public override HttpCachePolicyBase Cache { get { return TheCache; } }
public HttpCachePolicyBase TheCache { get; set; }
}
class HttpCachePolicyMock : HttpCachePolicyBase
{
private HttpCacheability _cacheability;
public override void SetCacheability(HttpCacheability cacheability)
{
_cacheability = cacheability;
}
public void ShouldHaveSetCacheabilityTo(HttpCacheability expectedCacheability)
{
Assert.AreEqual(expectedCacheability, _cacheability);
}
}
I have created two helper classes, one with the suffix -Stub and one with the suffix -Mock. The convention here is that a stub is a type of class used to provide a context to the class under test. Mocks also do that, but additionally a mock can make expectation about what should happen to it during the test.
Example #2: Testing an HTTP handler
[TestMethod]
public void ShouldRedirectAuthenticatedUser()
{
HttpServerUtilityMock httpServerUtilityMock = new HttpServerUtilityMock();
HttpContextStub httpContextStub = new HttpContextStub
{
TheRequest = new HttpRequestStub { IsItAuthenticated = true },
TheServer = httpServerUtilityMock
};
new RedirectAuthenticatedUsersHandler().TransferUserIfAuthenticated(httpContextStub);
httpServerUtilityMock.ShouldHaveTransferredTo("/farfaraway");
}
class HttpContextStub : HttpContextBase
{
public override HttpRequestBase Request { get { return TheRequest; } }
public override HttpServerUtilityBase Server { get { return TheServer; } }
public HttpRequestBase TheRequest { get; set; }
public HttpServerUtilityBase TheServer { get; set; }
}
class HttpRequestStub : HttpRequestBase
{
public override bool IsAuthenticated { get { return IsItAuthenticated; } }
public bool IsItAuthenticated { get; set; }
}
class HttpServerUtilityMock : HttpServerUtilityBase
{
private string _path;
public override void TransferRequest(string path)
{
_path = path;
}
public void ShouldHaveTransferredTo(string expectedPath)
{
Assert.AreEqual(expectedPath, _path);
}
}
No Comments »

WTF? I am quite sure that replacing ToLower() with ToUpperInvariant() will make my test fail…
1 Comment »
Posted by: admin in Microsoft technologies, Software development, tags: Agile, asp.net, c#, code quality, programming, system.web.abstractions, testability, testing, unit test
The testability of ASP.NET code has long been a challenge; creating unit tests for your ASP.NET code has been difficult. One of the main points of the new ASP.NET MVC framework has been to make code written for it easily testable. However, not many people know that in ASP.NET 3.5, Microsoft has added a few features to make any ASP.NET applications, not only ASP.NET MVC applications, more easy to test. The System.Web.Abstractions assembly adds a few classes to the System.Web namespace that will help the situation. For instance, looking at the documentation for System.Web.HttpRequestBase, it states that
The HttpRequestBase class is an abstract class that contains the same members as the HttpRequest class. The HttpRequestBase class enables you to create derived classes that are like the HttpRequest class, but that you can customize and that work outside the ASP.NET pipeline. When you perform unit testing, you typically use a derived class to implement members that have customized behavior that fulfills the scenario that you are testing.
Very well. Looking at the documentation for HttpRequest, we see that HttpRequest is not a decendent of HttpRequestBase as one might expect from the name. The reason for this is probably that that would break backwards compatability with older versions of ASP.NET. So, how can we exploit the HttpRequestBase then? The answer is the HttpRequestWrapper class which is a decendant of HttpRequestBase and has a constructor that takes an HttpRequest object as a parameter. Then, we can take the HttpRequest object passed to our code from the framework, wrap it inside an HttpRequestWrapper object and pass it on to our code as a HttpRequestBase object. As I will show you in the examples below, this will enable us to create unit tests of our code by creating fake implementations of ASP.NET framework clases (using Rhino.Mocks).
Example #1: Testing a page codebehind file
Take, for instance, this simple page codebehind code that we would like to test:
using System;
using System.Web;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Init(object sender, EventArgs e)
{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
}
}
The first step to take here, is to extract a method which take the request object as a parameter instead of fetching it from a method in a superclass. In general, this is a variation of the dependency injection pattern which in many situations will help us make our code testable (also, see my earlier related post). Like so:
using System.Web;
using System;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Init(object sender, EventArgs e)
{
SetCacheablityOfResponse(Response);
}
public void SetCacheablityOfResponse(HttpResponse response)
{
response.Cache.SetCacheability(HttpCacheability.NoCache);
}
}
So, then having extracted our code in a separate method, the next step is to change the parameter type of this method from HttpRequest to HttpRequestBase. Furthermore, when calling this method, we need to wrap the HttpRequest object by creating an instance of HttpRequestWrapper. The code, then, looks like this:
using System.Web;
using System;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Init(object sender, EventArgs e)
{
SetCacheablityOfResponse(new HttpResponseWrapper(Response));
}
public void SetCacheablityOfResponse(HttpResponseBase response)
{
response.Cache.SetCacheability(HttpCacheability.NoCache);
}
}
Having now prepared our code for testing, we can create a unit test where we test the SetCacheabilityOfResponse method:
[TestMethod]
public void ShouldSetNoCacheabilityOnDefaultPage()
{
_Default page = new _Default();
MockRepository mocks = new MockRepository();
HttpResponseBase responseStub = mocks.Stub<HttpResponseBase>();
HttpCachePolicyBase cachePolicyMock = mocks.CreateMock<HttpCachePolicyBase>();
With.Mocks(mocks).Expecting(delegate
{
SetupResult.For(responseStub.Cache).Return(cachePolicyMock);
cachePolicyMock.SetCacheability(HttpCacheability.NoCache);
LastCall.On(cachePolicyMock).Repeat.AtLeastOnce();
}).Verify(delegate
{
page.SetCacheablityOfResponse(responseStub);
});
}
If you are not familiar with Rhino.Mocks or any other mocking framework, there appears to be a lot going on in that test. The basic idea is that we create derivatives of the -Base classes and pass these to the code that we are going to test, mimicking the behavior of the “real” objects that the framework would pass our code at runtime. Also note that in this particular test we test the side effect of our code, namely that the code should call a the SetCacheability method with a specific parameter. This is achieved using a mock object.
Example #2: Testing an HTTP Handler
Given the following HTTP handler code:
using System;
using System.Web;
public class RedirectAuthenticatedUsersHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
if (context.Request.IsAuthenticated)
{
context.Server.TransferRequest("/farfaraway");
}
}
}
Again, we extract the code we want to test into a separate method, passing it a -Base object and wrap the object passed to us from the framework in a -Wrapper object:
using System;
using System.Web;
public class RedirectAuthenticatedUsersHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
TransferUserIfAuthenticated(new HttpContextWrapper(context));
}
public void TransferUserIfAuthenticated(HttpContextBase context)
{
if (context.Request.IsAuthenticated)
{
context.Server.TransferRequest("/farfaraway");
}
}
}
This allows us to create unit tests for the TransferUserIfAuthenticated method, for instance:
[TestMethod]
public void ShouldRedirectAuthenticatedUser()
{
RedirectAuthenticatedUsersHandler handler = new RedirectAuthenticatedUsersHandler();
MockRepository mocks = new MockRepository();
HttpContextBase httpContextStub = mocks.Stub<HttpContextBase>();
HttpRequestBase httpRequestBaseStub = mocks.Stub<HttpRequestBase>();
HttpServerUtilityBase httpServerUtilityMock = mocks.CreateMock<HttpServerUtilityBase>();
With.Mocks(mocks).Expecting(delegate
{
SetupResult.For(httpContextStub.Request).Return(httpRequestBaseStub);
SetupResult.For(httpContextStub.Server).Return(httpServerUtilityMock);
SetupResult.For(httpRequestBaseStub.IsAuthenticated).Return(true);
httpServerUtilityMock.TransferRequest("/farfaraway");
LastCall.On(httpServerUtilityMock).Repeat.AtLeastOnce();
}).Verify(delegate
{
handler.TransferUserIfAuthenticated(httpContextStub);
});
}
Summary
I have shown two very simple examples on how some of the classes in the System.Web.Abstractions assembly can help us test our ASP.NET code. I have used HttpResponseBase, HttpServerUtilityBase, HttpContextBase, HttpRequestBase, and HttpCachePolicyBase. Note that there are a number of classes available, so if you are faced with not being able to test your ASP.NET code because of dependencies to classes in the framework, take a look in the System.Web namespace and see if there are -Base classes that can help you out.
Testability is a large topic, and there is much to be said about it. I have shown a couple of very simple examples on how to improve testability. Testability has a lot to do with code design as well; in a real world I would write the test before writing the code and I would move my code out of codebehinds. Those topics are discussed a lot elsewere, hopefully this post will bring you a small step further in writing testable code.
3 Comments »
Found this nice page that summarizes how to set cache-related information in ASP.NET: ASP.NET Cache Examples and Overview
2 Comments »
I just came across Ken Schaefer’s blog, and I found that he has posted a series of excellent posts concerning various aspects of getting Integrated Windows Authentication / Kerberos to work on IIS:
Simply a great source of information!
No Comments »
It seems to me that collaboration is a hot topic in IT nowadays. With the emergence of social networking, a new breed of online collaboration is forming (sometimes referred to as enterprise 2.0). It strikes me that the new breed of tools to a large degree support a transformational leadership style instead of the more classic transactional leadership style.
For example, transactional leadership with support from “traditional” tools:
- The manager gives her subordinate an assignment to write some document enclosed in an email
- The subordinate receives the assignment in email, creates and writes a document, drop it to a company file share, and emails his boss to review the document
- The manager reviews the document and sends a response in email
- The subordinate updates the document according to his boss’ review and finalize the document. Then, he notifies his boss that the document is finished.
This would be an example of transformational leadership: The boss creates a Wiki page for the document, and invites her subordinate to participate, either by screen sharing or editing directly in the Wiki page, and they work on the document together. It might be that my view on transformational leadership is too simplified or misunderstood, but I think there is a link.
I think that starting to use new collaboration tools often would mean a shift in leadership style in the organization. These tools invites us to work differently, and will not gain their potential usage unless we are willing to let go of traditional ways of working. Starting to use collaboration tools thus benefits greatly from leadership buy-in, although not strictly necessary (it could emerge from the masses).
1 Comment »
According to this New York Times article, researchers at Stanford University vote in favor of starting all over, redesigning the Internet. I wonder if that is the way to go? At the same time, they suggest an evolutionary approach:
“They argue that their new strategy is intended to allow new ideas to emerge in an evolutionary fashion, making it possible to move data traffic seamlessly to a new networking world.”
The Internet has indeed been evolutionary, how can one prevent ending up in the same mess once again?
No Comments »
Found this nice article entitled RFID’s security problem. US authorities have started to use RFID tags in passports and driver’s licenses although the security of RFID for this purpose is highly questionable.
“Gigi Zenk, a spokesperson for the Washington State Department of Licensing, says that Washington has made it illegal for third parties to use data from RFID tags without the tag owners’ consent.”
Well, now I am relieved. Not.
No Comments »
One popular way to dismiss or select a product is by referring to the word ‘enterprise’. ‘No, we cannot use Ruby on Rails because it is not an enterprise platform’, an IT person might tell you. Or ‘our company needs an enterprise solution, so we will select the X suite from (big) company Y’. In the latter case, ‘enterprise solution’ is a synonym for ‘behemoth’. If you buy an enterprise solution, make sure that you are a big enough company to afford it. Neither the price up front or the implementation is going to be cheap. ‘Enterprise’ is one of those words that can mean anything. I would suggest that you ban the use of it. Whenever a person refer to a solution as an ‘enterprise solution’, ask him or her what it actually means. Don’t let them get away with it!
No Comments »
Posted by: vidarkongsli in Software development, System integration, tags: ajax, gartner, hype, jsr-168, mashup, portal, rss, widget, wsrp
Five years ago there was a lot of hype around portal technologies. (You know of which I speak; portlets, JSR-168, WSRP, etc.). In 2004, Gartner listed technologies such as JSR-168(Portlet Specification), JSR-170 (Content Repository for Java™ Technology API) and WSRP (Web Services for Remote Portlets) at the peak of their hype cycle in their “Hype Cycle for the Portal Ecosystem“. My impression is that since then those technologies have kind of faded away.
In my personal experience, I have not seen any really successful portal technology deployments. (Of course, I am not implying that there are none such in existence, only I haven’t seen them). I have participated in my share of portal technology implementation projects, but none of them, I my opinion, did live up to their promise. Now seeing that there is less and less talk about portals (except from some software vendors that still are eager to sell their products that they have invested a lot in), I am questioning the future of portal frameworks as we know them.
What value do portals add?
In a discussion around web 2.0 technologies, a corporate communications person in a large international telecommunications company stated something like (I don’t remember his exact words) “portals have not really caught on - after all people prefer to read their email in Outlook instead of settling with the inferior experience in a portal”. This is a good point - many of the corporate portals focus on bringing a subset of functionality of other applications into a portal or workspace. But what is really the value added? After all, Firefox gave us tabbed browsing that has been adopted by all major browser vendors. Switching between your webmail and your (web-based) CRM system is only a Ctrl-tab away… In most scenarios, integration of applications using portal products did not deliver more than that.
A portal will add value when it is a common entry point where you can start when wanting to access information or a certain functionality. A typical example of this would be your corporate intranet. But it does not mean that the functionality necessarily needs to be delivered through that portal. Rather, it should guide or direct you to that application which delivers that functionality - only a click away.
Another area where portals could add value, is if data/functionality from several applications can be combined to add value. This has been a promise from portal frameworks that in my opinion has only to a very limited degree has been delivered. Inter-portlet communication did not happen to any large extent.
What is the cost of portals?
Compared to a plain web server technologies like Java Servlets, ASP.Net and the like, portal frameworks not only typically represent an extra licensing expense, they add quite a bit of complexity. In addition to configuration complexity, there is added complexity associated with customization and development. For instance, development models for portals are heavier and so are the development environments. Furthermore, portal frameworks constrain you in several ways, for instance when changing the look-and-feel or user interface experience. What is relatively easy to change in a standard web platform is much harder to change in a portal.
With the emergence of agile methodologies, disciplines like test-driven development and automated testing has become something that we have learned to appreciate. This has shown to be another area where portal frameworks get in your way as a developer- they are inherently hard to test.
The challengers
With the emergence of web 2.0-technologies, backed up by large Internet companies like Google and Yahoo! that do not sell software but services, the focus seems to be on lightweight technologies like Ajax, mashups, RSS, and REST-based services. Widgets/gadgets like the ones offered by services like Netvibes, iGoogle, Yahoo! and live.com are the soupe du jour. They offer a light-weight development model with a very low startup cost; no specific server-side technology knowledge is required, no specialized IDE or dev tools required. The big question in my mind is whether these will challenge “traditional” portal technologies as the leading enabling technologies for intranet content aggregation? Quite recently Netvibes chose to open source their JavaScript widget engine. Furthermore, open source projects like Shindig are popping up that aims to offer developers frameworks for widget development.
Portal frameworks also continue to evolve. JSR-168 has been succeeded by JSR-286 and there is a version 2 of WSRP. The question is if this is enough to to make portlets prosper. Personally, I don’t think so as the problems are at a more fundamental, conceptual level than API specifications. But time will show…
In conclusion
“Traditional” portal frameworks have not lived up to their expectations. The use cases for portal technology represent niche functionality, at most. Furthermore, portal technology represent a heavy development model that in many cases will slow you down, compared to other technologies. If you are considering implementing portal technology in your company, you should very carefully investigate cost/benefit. Do not exclusively listen to portal vendors; talk to peer companies that have implemented portals, inquire them about their experiences. Talk to devs. Keep a close eye on emerging technologies. Keywords include widgets, Ajax, RSS, mashups.
No Comments »
|