In the previous post we looked at a very basic integration test with a TestServer setup. This in itself isn’t very helpful as tests, both unit and integration, are used for testing your own application or library function.

So how do we start up a test version of the application we want to test?

The below is all based on a File > New MVC Web Application in Visual Studio.

This can also be done by running dotnet new mvc on the command line.

Calling the Application Code

To do this we want to call the Startup class as the full application host builder does. This way all the service registrations etc. will be setup. To enable this we use the UseStartup extension method on the webHost we are configuring.

var hostBuilder = new HostBuilder()
    .ConfigureWebHost(webHost =>
    {
        // Add TestServer
        webHost.UseTestServer();
        webHost.UseStartup<WebApplication41.Startup>();
    });

And that is the only change to the previous builder version. We still build and start the host in the same way.

var host = await hostBuilder.StartAsync();

And we access a HttpClient instance to call the service in the same way.

var client = host.GetTestClient();

The Test in Full

Let’s take a look at the full integration test.

[Fact]
public async Task BasicEndPointTest()
{
    // Arrange
    var hostBuilder = new HostBuilder()
        .ConfigureWebHost(webHost =>
        {
            // Add TestServer
            webHost.UseTestServer();
            webHost.UseStartup<WebApplication41.Startup>();
        });

    // Create and start up the host
    var host = await hostBuilder.StartAsync();

    // Create an HttpClient which is setup for the test host
    var client = host.GetTestClient();

    // Act
    var response = await client.GetAsync("/Home/Test");

    // Assert
    var responseString = await response.Content.ReadAsStringAsync();
    responseString.Should().Be("This is a test");
}

The end point in question returns a basic ContentResult to the caller from the default HomeController.

public IActionResult Test()
{
    return Content("This is a test");
}

Conclusion

In this post we have looked at setting up a host for your application in a test. We have also shown how to call a basic end point in the integration test and check the Controller Action returns the expected value from your application.

Any questions/comments then please contact me on Twitter @WestDiscGolf

Part 1 - Integration Testing with ASP.NET Core 3.1

Part 2 - This post

Part 3 - Integration Testing with ASP.NET Core 3.1 - Swapping a dependency

Part 4 - Integration Testing with ASP.NET Core 3.1 - Remove the Boiler Plate

Part 5 - [Integration Testing with ASP.NET Core 3.1 - Swapping a Dependency with Moq][ParkFiveLink]

Part 6 - Integration Testing with ASP.NET Core 3.1 - Set Default Headers for All Clients