Jeff's Junk

The sillynonsense and .NET musings of Jeff Putz

News

My Sites

Unit testing with HttpContext

I've become a real fan of unit testing, though I was somewhat skeptical about its use in Web apps. NUnitASP is pretty cool for testing UI, but what I really needed was a way to test classes running in the context of a Web app, not actual requests for pages.

I do some caching voodoo in POP Forums to reduce database hits. Naturally this relies on the cache of the Web app, which you don't have in a unit testing context. Bummer! After some searching and link hopping I got to this article by Steve Padfield. Bam! That's what I needed. I only needed to make it work in .NET v2.

After some messing around, I arrived at this:

TextWriter tw = new StringWriter();
HttpWorkerRequest
wr = new SimpleWorkerRequest("/webapp", "c:\\inetpub\\wwwroot\\webapp\\", "default.aspx", "", tw);
HttpContext
.Current = new HttpContext(wr);

Pop that code in any test that will call a class that needs a non-null HttpContext. Works like a champ, and life is grand. Now if I can only get the damn tests, or the assembly being tested, to see my config settings.

Posted: May 31 2004, 07:42 PM by Jeff | with 6 comment(s)
Filed under: ,

Comments

steven said:

Hi there,
I'm just having a little trouble with this - trying to get the example from Steve Padfield's article working.
Have put your line in: HttpWorkerRequest wr = new SimpleWorkerRequest("/webapp", "c:\\inetpub\\wwwroot\\webapp\\", "default.aspx", "", tw);

...but get this exception:
System.Web.HttpException : Invalid use of SimpleWorkerRequest constructor. Application path cannot be overridden in this context. Please use SimpleWorkerRequest constructor that does not override the application path.

Can't find anything on google about it - - did you see this when you were trying things out?
Any ideas very gratefully received!
Thanks
S
# June 3, 2004 11:45 AM

Jeff said:

My example was on v2 of the framework, the alpha (May build). I don't think the current versions have the same overload, and as such you'd need to use Steve's code.
# June 3, 2004 7:54 PM

TrackBack said:

# June 4, 2004 11:30 PM

Karl said:

As far as I can tell, this has extremely limited capabilities. Namely, an HttpRuntime is never created, which renders all but basic unit testing useless.
# July 1, 2004 11:17 AM

Jeff said:

Useless? If I can store things in the cache, the only thing I've encountered that I need, then it's not useless at all. Just because you don't see a use for it doesn't mean other people might not.
# July 1, 2004 12:08 PM

Unit Testing with HttpContext « The Pursuit of a Life said:

Pingback from  Unit Testing with HttpContext « The Pursuit of a Life

# November 28, 2007 4:11 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)