使用Moq模拟AspnetMvc中的Request.Form
1、比如Request.Form["ddlType"]为control中需要模拟的内容
2、在单元测试中调用的代码(使用的是VS2010自带的单元测试框架)
var request = new Mock<HttpRequestBase>(); //request.Setup(r => r.HttpMethod).Returns("Post"); //这里Post和Get都行,可不添加此行代码 //request.Setup(r => r.PathInfo).Returns(string.Empty);//可不添加此行代码 //需要模拟的Request.Form键值对 var formvalues = new NameValueCollection { { "ddlType1", model.ddlType1}, { "ddlType2", model.ddlType2 } }; var mockHttpContext = new Mock<HttpContextBase>(); mockHttpContext.Setup(c => c.Request).Returns(request.Object); mockHttpContext.Setup(c => c.Request.Form).Returns(formvalues); Mock<EnterpriseRepository> mockEnterprise = new Mock<EnterpriseRepository>(); EnterpriseController controller = new EnterpriseController(mockEnterprise.Object); //Control var context = new ControllerContext(mockHttpContext.Object, new RouteData(), controller); controller.ControllerContext = context; //设置control的context熟悉 var result = controller.Create(model); //调用action方法