我正在创建一个名为ViewResult
的非常简单的JavaScriptViewResult
子类,在执行时会调用基本实现,然后将响应的Content-Type
设置为text/javascript
。在尝试对这个类进行单元测试时,我遇到了很多困难,它们实现了ASP.NET MVC堆栈的所有依赖项。
这是我使用Rhino的单元测试,到目前为止看起来是这样的:
[TestMethod]
public void TestExecuteAction()
{
var request = MockRepository.GenerateMock<HttpRequestBase>();
request.Expect(m => m.Url).Return(new Uri("/Test/JavaScript", UriKind.Relative));
var httpContext = MockRepository.GenerateMock<HttpContextBase>();
httpContext.Expect(m => m.Request).Return(request);
var controller = MockRepository.GenerateMock<ControllerBase>();
var virtualPathProvider = MockRepository.GenerateMock<VirtualPathProvider>();
var routeCollection = new RouteCollection(virtualPathProvider);
routeCollection.MapRoute("FakeRoute", "Test/JavaScript", new { controller = "Test", action = "JavaScript" });
var routeData = routeCollection.GetRouteData(httpContext);
var context = new ControllerContext(httpContext, routeData, controller);
var viewResult = new JavaScriptViewResult();
viewResult.ExecuteResult(context);
Assert.AreEqual("text/javascript", context.HttpContext.Response.ContentType);
}
运行测试时的最新异常是NullReferenceException
内的System.Web.Routing.Route.GetRouteData(HttpContextBase httpContext)
深。{/ p>
如何设置执行ViewResult
的所有依赖项?是否有任何技术可以使这更简单?或者,是否有不同的方法可以利用MVC视图引擎生成JavaScript,为响应设置正确的Content-Type
?
答案 0 :(得分:4)
我想出了如何满足ViewResult
的最低要求。我遇到的一个问题是嘲弄查找视图的过程。通过确保填充对象的View
属性可以避免这种情况。这是我的工作测试:
[TestMethod]
public void TestExecuteAction()
{
var response = MockRepository.GenerateStub<HttpResponseBase>();
response.Output = new StringWriter();
var httpContext = MockRepository.GenerateMock<HttpContextBase>();
httpContext.Expect(m => m.Response).Return(response);
var routeData = new RouteData();
routeData.Values.Add("action", "FakeAction");
var context = new ControllerContext(httpContext, routeData, MockRepository.GenerateMock<ControllerBase>());
var viewResult = new JavaScriptViewResult();
viewResult.View = MockRepository.GenerateMock<IView>();
viewResult.ExecuteResult(context);
Assert.AreEqual("text/javascript", context.HttpContext.Response.ContentType);
}