我正在创建一个名为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)

如何设置执行ViewResult的所有依赖项?有什么技巧可以简化这一过程?或者,是否有其他方法可以利用MVC视图引擎生成可以为响应设置适当的Content-Type的JavaScript?

最佳答案

我弄清楚了如何满足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);
}

关于c# - ASP.NET MVC 3 ViewResult子类的单元测试依赖项,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8661556/

10-15 03:07