我已经尝试了一段时间为ASP.NET MVC中的UserViewControl编写单元测试.我想得到看起来像这样的代码:
[TestMethod] public void HaveControlToDisplayThings() { var listControl = new ControlUnderTest(); var viewData = new ViewDataDictionary>(this.repo.GetMeSomeData()); // Set up a ViewContext using Moq. listControl.SetFakeViewContext(viewData); listControl.ViewData = viewData; listControl.RenderView(listControl.ViewContext); // Never got this far, no idea if this will work :) string s = listControl.ViewContext.HttpContext.Response.Output.ToString(); Assert.AreNotEqual(0, s.Length); foreach (var item in this.repo.GetMeSomeData()) { Assert.IsTrue(s.IndexOf(item) != -1); } }
不幸的是,无论我尝试什么,我都会从RenderView内部得到错误.这是由静态HttpContext.Current对象无用引起的(据我所知) - 我从中得到NullReferenceException
了System.Web.UI.Page.SetIntrinsics
.
我尝试使用Phil Haack的HttpSimulator,它给了我一个HttpContext对象,但我发现我还需要指定一个假HttpBrowserCapabilities
对象来进一步:
Subtext.TestLibrary.HttpSimulator simulator = new HttpSimulator(); simulator.SimulateRequest(); var browserMock = new Mock(); browserMock.Expect(b => b.PreferredRenderingMime).Returns("text/html"); browserMock.Expect(b => b.PreferredResponseEncoding).Returns("UTF-8"); browserMock.Expect(b => b.PreferredRequestEncoding).Returns("UTF-8"); HttpContext.Current.Request.Browser = browserMock.Object;
现在我在该对象的属性访问上获得了异常.我尽可能多地嘲笑,但似乎无处可逃.
有没有人设法做到这一点?