0

I have a method I need to unit test, which as the subject implies, generates a NameValueCollection. All properties of the NVC are populated through form data:

private NameValueCollection generateCollection()
{
   NameValueCollection nvc;
   nvc = new NameValueCollection();
   nvc.add("firstItem", HttpUtility.HtmlEncode(Request.Form["firstItem"]));
   nvc.add("secondItem", HttpUtility.HtmlEncode(Request.Form["secondItem"]));
   nvc.add("thirdItem", HttpUtility.HtmlEncode(Request.Form["thirdItem"]));

   return nvc;
}

I am using the unit testing features included with visual studio. How the heck do I do this?

mrwienerdog
  • 815
  • 3
  • 18
  • 35

1 Answers1

3

You need to change the method to take an HttpRequestBase.

You can then call it with a mocked version.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • Pardon me for sound like a complete idiot, but... I'm a student on a work placement, and just learning how to do a lot of these things. I am familiar with the (very) basics of unit testing in VS, but this is new... Could you point me in the direction of some materials that would help me through this? I am somewhat lost in what you mean by 'change the method to take an HttpRequestBase', and 'call it with a mocked version.' Apologies if I am asking too much.... – mrwienerdog Jun 18 '12 at 12:34
  • `Request` is a property in your (`Page`?) class that returns an `HttpRequest` instance. You're having trouble because you have no control over that. – SLaks Jun 18 '12 at 12:41
  • Instead, you should modify the method to take an `HttpRequestBase` as a parameter. When calling it normally, you can pass `new HttpRequestWrapper(Request)` (or create an overload that does that for you) – SLaks Jun 18 '12 at 12:41
  • For testing, you can create your own ("mock") class that inherits `HttpRequestBase` and returns whatever you want in the `Form` collection – SLaks Jun 18 '12 at 12:43
  • So, as a matter of best practice, when methods like these are written, HttpRequestBase is the way to go? (I didn't write the code, I just get to test it...). – mrwienerdog Jun 18 '12 at 12:46
  • @mrwienerdog: Yes. That's why ASP.Net MVC uses it exclusively. – SLaks Jun 18 '12 at 13:02
  • So for the purpose of helping an old dog who is trying to learn new tricks... Most of the things I've read about testing and HttpRequestBase all revolve around aspl.net MVC. However, the app I'm supposed to be testing is not based on MVC architecture. Was the guy that wrote this kinda crazy? I guess what I am saying is, did he use methods that are only (normally) used in an MVC in a non-MVC app? Is this a poor way to code? I know this is subjective, but I am curious.... – mrwienerdog Jun 18 '12 at 13:09