HttpRuntime vs HttpContext

Sometimes I find a discussion on something and I think to myself "you really need to blog this, because you may need to find it again some day and someone else might find it helpful." The adverse side effects of not doing this hit me the other day. I needed this little tidbit, but it took me a while to find it because I didn't blog it the last time I saw it! So here it is.

We're starting to put in some automated testing here at work (finally!), and we have some dependencies on elements in the Http world of ASP.NET. The problem when writing automated tests for web apps is that you do not have HttpContext.Current, which gives you access to some very important stuff, like HttpContext.Current.Request. Not surprisingly, that's not available during the execution of a unit test...because there is no web request!

The cache is one of the things that HttpContext.Current makes available. Fortunately, the cache can be used outside of an request by using HttpRuntime.Cache. Not only does this mean that you could write a winform app that uses the cache, but it also means that you can use it, and test it, in your automated tests.

The following is a short but significant discussion on the topic. If you're an ASP.NET guy, it is definitely worth your time reading it:


Anderson Imes (8/21/2007 11:27 AM)

You might consider refactoring your methods so that they don't have dependencies on context.  If you have methods that depend on context to execute, you are not "Unit" testing them, you are performing a functional test.

 It's a thin line and hard to keep straight, but basically your methods should be refactored to accept information that your presentation tier passes to them, rather than having them pull it straight out.  Once you have done this, you can perform a "real" unit test that only tests that one unit of code, without dependencies on your presentation tier.

 Good luck!