对ASP进行单元测试.. NET MVC 3 ViewResult子类

本文关键字:MVC ViewResult 子类 NET 单元测试 ASP | 更新日期: 2023-09-27 18:18:54

我正在创建一个非常简单的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);
}

运行测试时,最新的异常是System.Web.Routing.Route.GetRouteData(HttpContextBase httpContext)的内部深处的NullReferenceException

我如何设置执行ViewResult的所有依赖关系?有没有什么技巧可以让它变得更简单?另外,是否有一种不同的方式,我可以利用MVC视图引擎来生成JavaScript,将设置适当的Content-Type响应?

对ASP进行单元测试.. NET MVC 3 ViewResult子类

我想出了如何满足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);
}