Mock Request.Form & Request.QueryString for unit tests
在我们的一些Mvc controller中,有时直接通过Request.Form["key"] 取值,而Form collection 是只读的集合,我们可以通过如下方式mock出需要的Form集合或者url的query字符串。
public static void MockControllerContext(this BaseController baseController, string requestUri = "https://test.com", NameValueCollection requestForm = null, NameValueCollection requestQueryString = null) { var mockControllerContext = new Mock<ControllerContext>(); var mockHttpContextBase = new Mock<HttpContextBase>(); var mockHttpResponseBase = new Mock<HttpResponseBase>(); var mockHttpRequestBase = new Mock<HttpRequestBase>(); mockHttpRequestBase.Setup(x => x.Url) .Returns(new Uri(requestUri)); mockHttpRequestBase.Setup(x => x.Form) .Returns(requestForm); mockHttpRequestBase.Setup(x => x.QueryString) .Returns(requestQueryString); mockHttpResponseBase.Setup(x => x.OutputStream) .Returns(new MemoryStream()); mockHttpResponseBase.Setup(x => x.Output) .Returns(new StringWriter()); mockHttpContextBase.Setup(x => x.Response) .Returns(mockHttpResponseBase.Object); mockHttpContextBase.Setup(x => x.Request) .Returns(mockHttpRequestBase.Object); mockControllerContext.Setup(x => x.HttpContext) .Returns(mockHttpContextBase.Object); baseController.ControllerContext = mockControllerContext.Object; }
在单元测试的方法里面如下方式去使用:
var nameValues = new NameValueCollection { { "key", "value" } }; _testController.MockControllerContext(requestForm: nameValues);