编程语言
首页 > 编程语言> > c#-ASP.NET MVC 3 ViewResult子类的单元测试依赖项

c#-ASP.NET MVC 3 ViewResult子类的单元测试依赖项

作者:互联网

我正在创建一个名为JavaScriptViewResult的非常简单的ViewResult子类,该子类在执行时调用基本实现,然后将响应的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,该JavaScript将为响应设置适当的Content-Type?

解决方法:

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

标签:unit-testing,viewresult,c,asp-net-mvc-3,rhino-mocks
来源: https://codeday.me/bug/20191101/1986909.html