codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Follow publication

Integration Tests for ASP.NET Core Web APIs using MSTest

How to write integration tests for API endpoints using MSTest

Changhui Xu
codeburst
Published in
4 min readJan 25, 2021

--

We often want to write integration tests to evaluate our app’s whole request-response pipeline. For example, we want our API endpoints to return the same responses given the same requests. These integration tests are helpful in catching cases of missing properties in the JSON responses, mismatching upper/lower cases of property names, obsolete error messages, and so on.

The ASP.NET official documentation has an article entitled Integration tests in ASP.NET Core, which covers lots of aspects of integration tests in ASP.NET Core using the xUnit test framework. However, the magical IClassFixture<T> in xUnit creates confusion and difficulties for developers who are more familiar with other test frameworks. For instance, this GitHub issue points out the gap in developers’ expectations of the documentation on integration tests.

Here I am not going to steal the show from the ASP.NET Docs, and all the goodies are still in the official documentation. In this article, I will try to fill in the gap and show you how to write integration tests using MSTest. You can find my demo solution in this GitHub repository.

Basic tests with the default WebApplicationFactory

First, we need to install the Microsoft.AspNetCore.Mvc.Testing NuGet package. This package includes the Microsoft.AspNetCore.TestHost NuGet package, which will help us to create the test web host and in-memory test server. Especially, the Microsoft.AspNetCore.Mvc.Testing NuGet package provides the WebApplicationFactory class to streamline bootstrapping the system-under-test (SUT) with TestServer.

When using the xUnit framework, we write the test class by inheriting from IClassFixture<WebApplicationFactory<MyProject.Startup>>. The equivalent way in MSTest is to use the ClassInitialize attribute and the ClassCleanup attribute, which are responsible for creating the shared test context and disposing it. The following code snippet shows an example integration test for an action method in a web API controller.

--

--

Published in codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Written by Changhui Xu

Lead Application Developer. MBA. I write blogs about .NET, Angular, JavaScript/TypeScript, Docker, AWS, DDD, and many others.

Responses (1)

Write a response