Integration testing an MVC application without the pain of UI automation

ぐ巨炮叔叔 提交于 2019-12-03 17:15:42

If you want to do automated end-to-end testing of an ASP.NET MVC application without going through the UI, one good way to do it is to programmatically send HTTP requests to the different URLs and assert the state of the system afterwards.

Your integration tests would basically look like this:

  1. Arrange: Start a web server to host the web application under test
  2. Act: Send an HTTP request to a specific URL, which will be handled by a controller action
  3. Assert: Verify the state of the system (e.g. look for specific database records), or verify the contents of the response (e.g. look for specific strings in the returned HTML)

You can easily host an ASP.NET web app in an in-process web server using CassiniDev. Also, one convenient way to send HTTP requests programmatically is to use the Microsoft ASP.NET Web API Client Libraries.

Here's an example:

[TestFixture]
public class When_retrieving_a_customer
{
    private CassiniDevServer server;
    private HttpClient client;

    [SetUp]        
    public void Init()
    {
        // Arrange
        server = new CassiniDevServer();
        server.StartServer("..\relative\path\to\webapp", 80, "/", "localhost");
        client = new HttpClient { BaseAddress = "http://localhost" };
    }

    [TearDown]
    public void Cleanup()
    {
        server.StopServer();
        server.Dispose();
    }

    [Test]
    public void Should_return_a_view_containing_the_specified_customer_id()
    {
        // Act
        var response = client.GetAsync("customers/123").Result;

        // Assert
        Assert.Contains("123", response.Content.ReadAsStringAsync().Result);
    }
}

If you're looking for a more complete example of this technique in action, you can find it in a sample MVC 4 web application of mine, where I demonstrated it in the context of writing automated acceptance tests.

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