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...a nightmare.
public static bool IsPowerUser
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 :).