Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking HttpRequest.Form for unit tests

In ASP.NET, I'm trying to mock up a unit test using the HttpRequest object. The Form collection of the object is indicating the collection is readonly. Is there a way to implement this behavior for my unit tests without having to provide my own httprequest implemenation? The following snippet fails with request.Form being readonly. Tx.

var request = new HttpRequest("", "http://localhost" + url, "");
request.Form["__EVENTTARGET"] = eventTarget;
AutorefreshSessionHelper.IsRequestForAutoRefresh(request);
like image 310
Brett Avatar asked Mar 09 '23 16:03

Brett


1 Answers

This snippet enables writing to Form collection and then disables it again. Tested on ASP.NET 3.5.

var request = new HttpRequest("", url, "");
var formType = request.Form.GetType();
formType.GetMethod("MakeReadWrite", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).Invoke(request.Form, null);

request.Form["__EVENTTARGET"] = eventTarget;

formType.GetMethod("MakeReadOnly", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).Invoke(request.Form, null);
like image 138
Gedas Kutka Avatar answered Mar 20 '23 17:03

Gedas Kutka