Can I test an ASP.NET MVC web project using Selenium from a unit test project in the same solution?

♀尐吖头ヾ 提交于 2019-12-20 05:25:08

问题


I have an ASP.NET MVC 5 web project, and I have an MsTest-based unit test project that uses Selenium to do some automated "browser" tests.

Currently, I have to run the web project (in my local IIS Express) and then run the tests against that, but that has all kinds of restrictions. For example, I can only "run" the tests, I can't "debug" them. And clearly this doesn't play well with my continuous integration pipeline.

Is there no way to have the tests spin up an instance of the website? (I know that ASP.NET MVC 6 can be self-hosted, so that might open up some possibilities, but this project will be stuck on MVC 5).


回答1:


OK, here's a way to do it:

  1. Spin up a web server in a method decorated with the [AssemblyInitialize] attribute (this method must be in a class in your test project decorated with the [TestClass] attribute).

    [AssemblyInitialize]
    public Initialize()
    {
        ...
    }
    
  2. Stop the web server in a method decorated with the [AssemblyCleanup] attribute.

    [AssemblyCleanup]
    public Cleanup()
    {
        ...
    }
    

To start IIS Express you can just use Process.Start on IISExpress.exe, passing in the path and port arguments. (To stop it, you can simply kill the process you started). See the link in Fran's answer for an example.

The path argument should point to the folder containing your website project (the project folder, not the bin folder).

The port argument needs to be the same local port number used when you run the website locally (so if the URL in the browser window is http://localhost:57941 then the port number you need is 57941).




回答2:


I'm not sure how you'd do this with just Selenium. Selenium is just automating browser processes. you might be able to write a script or you could use a testing framework like SpecFlow to start up a webserver before your test run.

http://www.radicalgeek.co.uk/Post/12/starting-up-iis-express-for-a-specflow-and-selenium-webdriver-test-run

Archived link in case the first one does not work: https://web.archive.org/web/20160927003518/http://www.radicalgeek.co.uk/Post/12/starting-up-iis-express-for-a-specflow-and-selenium-webdriver-test-run



来源:https://stackoverflow.com/questions/33691016/can-i-test-an-asp-net-mvc-web-project-using-selenium-from-a-unit-test-project-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!