2

我在 Visual Studio 2010 中创建了一个默认的 MVC 4.0 Internet Web 应用程序。在自动生成的主控制器方法之一上,我右键单击并创建了一个单元测试。我选择了一个单独的/新项目。测试代码如下所示:

    /// <summary>
    ///A test for Index
    ///</summary>
    // TODO: Ensure that the UrlToTest attribute specifies a URL to an ASP.NET page (for example,
    // http://.../Default.aspx). This is necessary for the unit test to be executed on the web server,
    // whether you are testing a page, web service, or a WCF service.
    [TestMethod()]
    [HostType("ASP.NET")]
    [AspNetDevelopmentServerHost("E:\\Backup 20080915\\Projects\\Writing Projects\\Blogs\\31a\\QUnitMVC\\jQueryMvcWebApp\\jQueryMvcWebApp", "/")]
    [UrlToTest("http://localhost:61524/")]
    public void IndexTest()
    {
        HomeController target = new HomeController(); // TODO: Initialize to an appropriate value
        ActionResult expected = null; // TODO: Initialize to an appropriate value
        ActionResult actual;
        actual = target.Index();
        Assert.AreEqual(expected, actual);
        Assert.Inconclusive("Verify the correctness of this test method.");
    }

如果我运行完全由 VS 编写的测试,它会失败并显示:

Failed  IndexTest   jQueryMvcWebApp.Test.HomeControllerTest.IndexTest   The Web request 'http://localhost:61524/' completed successfully without running the test. This can occur when configuring the Web application for testing fails (an ASP.NET server error occurs when processing the request), or when no ASP.NET page is executed (the URL may point to an HTML page, a Web service, or a directory listing). Running tests in ASP.NET requires the URL to resolve to an ASP.NET page and for the page to execute properly up to the Load event. The response from the request is stored in the file 'WebRequestResponse_IndexTest.html' with the test results; typically this file can be opened with a Web browser to view its contents.     

如果我注释掉以下 3 个属性,测试将按预期运行:

[HostType("ASP.NET")]
[AspNetDevelopmentServerHost("E:\\Backup 20080915\\Projects\\Writing Projects\\Blogs\\31a\\QUnitMVC\\jQueryMvcWebApp\\jQueryMvcWebApp", "/")]
[UrlToTest("http://localhost:61524/")]

所以我的问题是,为什么它们是默认设置,我什么时候应该不注释它们?

4

1 回答 1

0

如果您仔细阅读错误消息,您就会明白原因。您实际上并未加载可以成功访问 Load 事件的 ASP.NET 页面。您正在运行 MVC,它实际上没有“页面”。我对我的每一个控制器/动作进行了全面的单元测试,而且我从未尝试过使用这些属性。可能是在 Visual Studio 测试中为任何 .net Web 应用程序默认这些属性 - 实际上它应该只用于 Web 表单应用程序。

于 2012-12-30T03:30:57.607 回答