Artificially populate HttpContext object in a Console application

I am writing a wrapper library for log4net. This library should be able to capture Context information such as querystring, cookie, form fields etc. etc.

I am invoking this wrapper class from Console application as opposed to TDD class.

Is there a way to populate HttpContext object inside a Console application as follows?

HttpContext c = new HttpContext(null);
c.Request.QueryString.Keys[1] = "city";
c.Request.QueryString[1] = "Los Angeles";
c.Request.QueryString.Keys[2] = "state";
c.Request.QueryString[2] = "CA";

And then retrieve it as follows?

Console.WriteLine(context.Request.QueryString.Keys[1]);

I am getting the following exception when I attempt the above code.

Property or indexer 'System.Collections.Specialized.NameObjectCollectionBase.KeysCollection.this[int]' cannot be assigned to -- it is read only

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

you can read here on using Moq to fake it out:
http://o2platform.wordpress.com/2011/04/05/mocking-httpcontext-httprequest-and-httpresponse-for-unittests-using-moq/

Method 2

It’s not easily possible to mock a HttpContext. You could use Typemock Isolator to setup the context but its not free. Another (better) approach would be to abstract the HttpContext and implement your console (test?) client against a mock implementation of the abstraction


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x