Juri Strumpflohner
Juri Strumpflohner Juri is a full stack developer and tech lead with a special passion for the web and frontend development. He creates online videos for Egghead.io, writes articles on his blog and for tech magazines, speaks at conferences and holds training workshops. Juri is also a recognized Google Developer Expert in Web Technologies

A Test-Driven Dev's Nightmare: Meeting the HttpContext

2 min read

My main task for the coming weeks at work is to extend one of our older but highly successful web application with new functionalities. The webapp has become quite complex over the years, as it happens with most applications when they're being extended. Unfortunately, devs have not written any automated tests. Not having any tests in place that could function as regression suite is quite bad, as any change turns out to be risky because you don't have any certainty on whether you didn't destroy any previously implemented functionalities.

So what I started with was to create a unit-test project and to write some tests that did at least cover the areas where I was going to modify code. My good intentions didn't last long...one of my tests immediately failed, returning
Object reference not set to an instance of an object
"I probably need to mock something out", I thought...navigated to the code where the exception occurred and  ... gave up. A static helper class used throughout the whole business logic accessing the ASP.net HttpContext...

public static class SomeHelper
{
...
public static bool IsPowerUser
{
get
{
return HttpContext.Current.User.IsInRole(AccountRoles.Office.ToString())
&& HttpContext.Current.User.IsInRole(AccountRoles.PowerUser.ToString());
}
}
...
}
...a nightmare.

So, what's wrong with this?
The class from which the code excerpt has been taken, is part of the business layer of the application which resides in a separate dll. Now the business layer should be generic and independent of the used UI technology. In this way the same BL layer could be used in a WinForms or WebForms or ASP.net MVC project. Therefore, since the HttpContext is a UI technology dependent component, referencing it from the BL layer is inherently bad.

Instead, the current user's role should be verified through the Principal associated to the current thread. Not only this is the better alternative because your BL layer remains independent from the used UI technology, but also because the thread's principal can be mocked, while the HttpContext cannot. I've seen approaches for mocking the MVC's HttpContext but not the one of classic ASP.net WebForms projects. But if you know an implementation, I'm highly interested of course :).
Questions? Thoughts? Hit me up on Twitter
comments powered by Disqus