如何以编程方式启动 ASP.NET MVC 应用程序并与之交互?

Sam*_*Sam 5 .net asp.net-mvc integration-testing

我正在开发 ASP.NET MVC 应用程序。它HttpApplication看起来像这样:

public class MvcApplication : HttpApplication
{
    protected void Application_Start()
    {
        //Do some sort of initialisation. Set the DependencyResolver.
    }
}
Run Code Online (Sandbox Code Playgroud)

对于集成测试,我想以编程方式启动应用程序并使用它DependencyResolver与之交互。访问DependencyResolver似乎很容易,因为我只需调用DependencyResolver.Current. 但是,我还没有弄清楚如何让应用程序初始化逻辑运行。

我尝试过调用new MvcApplication().Init(),但这似乎没有触发Application_Start方法调用。我尝试继承MvcApplication并提供对直接 call 的访问Application_Start,但由于 ASP.NET MVC 的异常而失败。

Adr*_*ian 0

您可以使用 Selenium WebDriver 来集成测试 MVC 应用程序。您可以通过对 Web 浏览器要执行的操作进行编码,以编程方式与应用程序 UI 进行交互。然后可以从 MSTest 运行集成测试,以便您可以针对 UI 编写断言。这是有关 Selenium 的文档http://docs.seleniumhq.org/docs/03_webdriver.jsp

这是一个代码示例:

    [TestMethod]
    public void runUITest()
    {
        driver = new FirefoxDriver(); //launches a Firefox window so you can observe the test run
        driver.Manage().Timeouts().ImplicitlyWait(new TimeSpan(0, 0, 7));                
        driver.Navigate().GoToUrl("http://localhost/yourWebApp"));
        //assert something
Assert.IsTrue(driver.FindElement(By.XPath("//fieldset[@id='YourControl']/div/div[2]/label/span/span")).Displayed);
        //find an element and click it
        driver.FindElement(By.Id("FormSubmitButton")).Click();           
    }
Run Code Online (Sandbox Code Playgroud)

Selenium WebDriver 可作为 NuGet 包使用。