使用ASP.NET Dev Server进行单元测试MVC

Bre*_*ias 6 c# asp.net asp.net-mvc unit-testing visual-studio

我想确认我的"HomeController"类是由我创建的路由选择的.所以我有这样的测试:

    [TestMethod]
    [UrlToTest("http://localhost:14478/home")]
    [HostType("ASP.NET")]
    [AspNetDevelopmentServerHost("$(SolutionDir)\\MvcBuildApp")]
    public void MyTest()
    {
        System.Diagnostics.Debugger.Break();

        RouteCollection routes = new RouteCollection();
        MvcApplication.RegisterRoutes(routes);
        MvcApplication.RegisterGlobalFilters(GlobalFilters.Filters);
        //This fetches DefaultControllerFactory (for now, anyway...)
        var factory = ControllerBuilder.Current.GetControllerFactory();
        //mock a context...
        var httpContext = CreateHttpContext("http://localhost:14478/home", "GET");
        RouteData route = routes.GetRouteData(httpContext);

        var ctrlInstance = factory.CreateController(new RequestContext(httpContext, route), (string)route.Values["controller"]);

        //ASSERT the instance is of type "HomeController"
        //...
     }
Run Code Online (Sandbox Code Playgroud)

说它失败了 'http://localhost:14478/home' completed successfully without running the test.

我注意到在VS输出窗口中,还有这条消息No connection could be made because the target machine actively refused it 127.0.0.1:14478.我认为卡西尼一定不能活跃.所以我选择在启动单元测试之前启动正在测试的站点(ctrl + F5).然后它将VS输出更改为:

WebTestAdapter.ConnectToHostAdapter:发生意外异常.Microsoft.VisualStudio.TestTools.HostAdapters.AbortTestExecutionException:应用程序中的错误.在Microsoft.VisualStudio.TestTools.HostAdapters.WebTestAdapter.ConnectToHostAdapter()

为了解决这个问题,我遵循了这些文章的建议:

......但无论我做什么,我仍然会得到错误.建议?

更新/澄清
这个问题不是关于测试MVC路由.此问题的目的是发现如何正确初始化ASP.NET MVC以允许更"深入"的自动化测试.我仅针对DefaultControllerFactory选择了"路由测试"场景,仅作为示例.在此示例中,除非正确初始化ASP.NET MVC,否则DefaultControllerFactory的行为不正常.

Jes*_*sse 0

您可能有兴趣查看 Steve Sanderson 的 MVC 测试框架。如果您下载源代码,您将获得一个关于如何初始化 MVC 框架的很好的示例:

http://blog.codeville.net/2009/06/11/integration-testing-your-aspnet-mvc-application/