Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why mock HttpContext if it can be constructed?

I have always been faking/mocking/stubbing HttpContext somehow in ASP.NET (much easier in ASP.NET MVC/MonoRail).

But I can see that HttpContext itself can be constructed easily, literally with couple of lines of code.

var tw = new StringWriter();
var workerReq = new SimpleWorkerRequest("/webapp", @"c:\here\there\wwwroot", "page.aspx", tw);
var context = new HtpContext(workerReq);

If we'll wrap this code into something like this it should work fine, and probably we can even render ASPX using that:

using(Simulate.HttpContext()) {
  HttpContext.Current.BlaBla;
}

So the questions are:

  1. Reasons why it should NOT be done.
  2. Reasons why it SHOULD be done.
  3. Why it is not widely used (in fact I do not remember ANY posts about it).

I remember one post where Phill Haack constructed HttpContext using Reflection hacks.
But it seems it is just not needed.

Cheers,
Dmitriy.

like image 602
Dmytrii Nagirniak Avatar asked Nov 06 '09 10:11

Dmytrii Nagirniak


1 Answers

It's fine for doing very simple testing, but how would you unit test a component which uses HttpRequest.Files? As far as I know there are no public APIs to allow you to specify this on SimpleWorkerRequest. Even if you could find a location where you could set an HttpFileCollection property, note that its constructor is internal, so you can't even create an instance of that type.

HttpRequest.Files is not alone in this regard, and in fact there are probably vastly more things you can't test with the current HttpContext implementation than you can test. This is where abstractions really come in handy.

like image 166
Levi Avatar answered Oct 12 '22 14:10

Levi