我是Nunit和Moq框架的新手,我完全陷入测试我的一个控制器,因为它从Request.Form [“Something”]中获取了一些值。我能够使用nunit测试控制器方法的其他部分,但代码在同一个控制器中获取Request.form值的任何地方都会中断。
下面是使用nunit和Moq的测试控制器代码:
[Test]
public void SaveRequest()
{
TestController test = new TestController();
TestModel model = new TestModel();
model = PopulateRequestModel();
Mail = model.Mail;
HttpContext.Current = new HttpContext(new HttpRequest("", "https://localhost", ""), new HttpResponse(new System.IO.StringWriter()));
System.Web.SessionState.SessionStateUtility.AddHttpSessionStateToContext(HttpContext.Current, new HttpSessionStateContainer("", new SessionStateItemCollection(), new HttpStaticObjectsCollection(), 20000, true, HttpCookieMode.UseCookies, SessionStateMode.InProc, false));
System.Web.HttpContext.Current.Session["__RequestVerificationTokenError"] = false;
var httpContext1 = (new Mock<HttpContextBase>());
var routeData = new RouteData();
httpContext1.Setup(c => c.Request.RequestContext.RouteData).Returns(routeData);
httpContext1.Setup(c => c.Request.Form).Returns(delegate()
{
var nv = new NameValueCollection();
nv.Add("Firstname", "Dave");
nv.Add("LastName", "Smith");
nv.Add("Email", "jsmith@host.com");
nv.Add("Comments", "Comments are here...");
nv.Add("ReceiveUpdates", "true");
return nv;
});
if (LoggedInEnterpriseId != null)
{
ViewResult result = test.SaveRequest(model, mail) as ViewResult;
Assert.IsNotNull(result);
}
}
PopulateRequestModel:
private RequestModel PopulateRequestModel ()
{
RequestModel model = new RequestModel ();
model.Firstname = "Dave";
model.LastName = "Smith";
model.Email = "jsmith@host.com";
model.Comments = "Comments are here...";
model.ReceiveUpdates = true;
return model;
}
以下是要测试的实际控制器方法:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SaveRequest(TestModel model, HttpPostedFileBase Mail)
{
string Name = Request.Form["Firstname"].ToString();
model.Mail = Mail;
//Start Adding Request to DB
Logger.Write("Start: Adding new request..");
try
{
using (db = new DatabaseContext())
{
NewRequest newRequest = new NewRequest();
if (RequestNumber != 0)
{
newRequest.Name = Convert.ToInt16(Request.Form["Firstname"]);
newRequest.LastName = Request.Form["LastName"];
newRequest.Email = Request.Form["Email"];
newRequest.Comments = Request.Form["Comments"];
newRequest.ReceiveUpdates = Convert.ToBoolean(Request.Form["ReceiveUpdates"]);
}
else
{
newRequest.Name = model.Firstname;
newRequest.LastName = model.LastName;
newRequest.Email = model.Email;
newRequest.Comments = model.Comments;
newRequest.ReceiveUpdates = model.ReceiveUpdates;
}
db.NewRequests.Add(newRequest);
int save = db.SaveChanges();
}
在使用request.form的地方,代码被阻止。