在 Web 中进行测试驱动的开发,比较大的困难是模拟 HttpContext ,它太复杂了。
moq 框架提供了强大的模拟能力,但是,模拟一个 HttpContext 对象还是需要自己来动手。
为此,我自己写了一个方法来完成这个工作。其中,还顺便使用 Log4Net 来输出一下它的工作情况。
/// <summary> /// 创建上下文模拟对象 /// 至少需要支持 /// Request 中 /// AppRelativeCurrentExecutionFilePath, /// ApplicationPath /// PathInfo /// Response 中 /// ApplyAppPathModifier /// </summary> /// <returns></returns> private Moq.Mock<System.Web.HttpContextBase> CreateHttpContext() { log4net.ILog log = log4net.LogManager.GetLogger("CreateHttpContext"); string ApplicationPath = "/"; string PathInfo = ""; string AppRelativeCurrentExecutionFilePath = "~/"; var contextMock = new Moq.Mock<System.Web.HttpContextBase>(); contextMock .Setup(c => c.Request.AppRelativeCurrentExecutionFilePath) .Returns(AppRelativeCurrentExecutionFilePath) .Callback(() => log.Info("Calling AppRelativeCurrentExecutionFilePath")); contextMock .Setup(c => c.Request.ApplicationPath) .Returns(ApplicationPath) .Callback(() => log.Info("Calling ApplicationPath")); contextMock.Setup(rc => rc.Request.PathInfo) .Returns(PathInfo) .Callback(() => log.Info("Calling PathInfo")); contextMock .Setup(rc => rc.Response.ApplyAppPathModifier(Moq.It.IsAny<string>())) .Returns((string s) => s) .Callback((string s) => log.InfoFormat("Calling ApplyAppPathModifier: {0}.", s)); return contextMock; }
虽然这个方法已经能够完成我需要的测试,但是,我希望能将它提炼一下,得到一个更加通用的 Mock 方法。
很快,我发现这个工作已经在很久以前被 Scott Hanselman 介绍过一次了,其中甚至还写了不同的 Mock 框架下的提供方法。不过 moq 版本的作者不是他,而是另外一个人 Daniel Cazzulino, 这篇文章你可以在这里找到:http://www.hanselman.com/blog/ASPNETMVCSessionAtMix08TDDAndMvcMockHelpers.aspx,还可以顺便看一下 Daniel Cazzulino 的博客:http://blogs.clariusconsulting.net/kzu/
不过,他的文章是在 2008 年写的,实在太古老了。当时还是 MVC 的 Preview2 ,moq 在那个时候就已经诞生了,看来我太孤陋寡闻了。
回到我们的主题,经过了这么长的时间,moq 已经有了一些变化,使用最新的 moq 语法修改之后,发现他的的代码没有能够通过测试。
与我的比较一下,发现其中少了对 Response 中 ApplyAppPathModifier 方法的支持,增加之后就正常了。
下面是修改之后的代码,希望能给你带来方便。
using System; using System.Web; using System.Text.RegularExpressions; using System.IO; using System.Collections.Specialized; using System.Web.Mvc; using System.Web.Routing; using Moq; namespace UnitTests { public static class MvcMockHelpers { public static HttpContextBase FakeHttpContext() { var context = new Mock<HttpContextBase>(); var request = new Mock<HttpRequestBase>(); var response = new Mock<HttpResponseBase>(); var session = new Mock<HttpSessionStateBase>(); var server = new Mock<HttpServerUtilityBase>(); // 必须要设置 Response 的 ApplyAppPathModifier 方法支持 response .Setup(rsp => rsp.ApplyAppPathModifier(Moq.It.IsAny<string>())) .Returns((string s) => s); context.Setup(ctx => ctx.Request).Returns(request.Object); context.Setup(ctx => ctx.Response).Returns(response.Object); context.Setup(ctx => ctx.Session).Returns(session.Object); context.Setup(ctx => ctx.Server).Returns(server.Object); return context.Object; } public static HttpContextBase FakeHttpContext(string url) { HttpContextBase context = FakeHttpContext(); context.Request.SetupRequestUrl(url); return context; } // Controller 的一个扩展方法 public static void SetFakeControllerContext(this Controller controller) { var httpContext = FakeHttpContext(); ControllerContext context = new ControllerContext(new RequestContext(httpContext, new RouteData()), controller); controller.ControllerContext = context; } static string GetUrlFileName(string url) { if (url.Contains("?")) return url.Substring(0, url.IndexOf("?")); else return url; } static NameValueCollection GetQueryStringParameters(string url) { if (url.Contains("?")) { NameValueCollection parameters = new NameValueCollection(); string[] parts = url.Split("?".ToCharArray()); string[] keys = parts[1].Split("&".ToCharArray()); foreach (string key in keys) { string[] part = key.Split("=".ToCharArray()); parameters.Add(part[0], part[1]); } return parameters; } else { return null; } } // 扩展 HttpRequestBase public static void SetHttpMethodResult(this HttpRequestBase request, string httpMethod) { Mock.Get(request) .Setup(req => req.HttpMethod) .Returns(httpMethod); } // 设置请求的地址 public static void SetupRequestUrl(this HttpRequestBase request, string url) { log4net.ILog log = log4net.LogManager.GetLogger("CreateHttpContext"); if (url == null) throw new ArgumentNullException("url"); if (!url.StartsWith("~/")) throw new ArgumentException("Sorry, we expect a virtual url starting with \"~/\"."); var mock = Mock.Get(request); mock.Setup(req => req.QueryString) .Returns(GetQueryStringParameters(url)); mock.Setup(req => req.AppRelativeCurrentExecutionFilePath) .Returns(GetUrlFileName(url)) .Callback(() => log.Info("Calling AppRelativeCurrentExecutionFilePath")); mock.Setup(req => req.PathInfo) .Returns(string.Empty); } } }