views:

356

answers:

2

I have 2 routes registered as follows:

routes.MapRoute("GetAnEmail", "{controller}", new { controller = "Home", action = "GetAnEmail" }, new { httpMethod = new HttpMethodConstraint("POST") })
routes.MapRoute("Home", "{controller}/{action}", new { controller = "Home", action = "Index" })

I have a valid unit test for the Home controller as follows:

 [Test]
 public void CanVerifyRouteMaps()
     {
         "~/".Route().ShouldMapTo<HomeController>(x => x.Index());
     }

I know GetAnEmail works, but how does one unit test a POSTed route?

+1  A: 

You need to simulate a post in your unit test.

System.Net.WebRequest req = System.Net.WebRequest.Create("your url");

req.ContentType = "text/xml";
req.Method = "POST";

byte[] bytes = System.Text.Encoding.ASCII.GetBytes("Your Data");
req.ContentLength = bytes.Length;
os = req.GetRequestStream();
os.Write(bytes, 0, bytes.Length); 


System.Net.WebResponse resp = req.GetResponse();
if (resp == null) return;
System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());

str responsecontent = sr.ReadToEnd().Trim();
Gratzy
+1  A: 

Gratzy's answer is close but all that is showing me is how to do a POST through code.

I think the solution is hinted at in Stephen Walther's blog post. I'm really testing my route constraint here, which is key. Stephen creates a fake httpContext in his example. I'm going to attempt this with Rhino Mocks and once I have a working example, will post back. If someone has already done this with Rhino Mock or Moq, please post up too.

LordHits