Testing ASP.NET Core Web APIs

Hello, Khabrovites! For future students on the "C # ASP.NET Core Developer" course , we publish a translation of a useful article.


API ASP.NET Core 2.1 Web API , . . API, , API.

InfoQ « -API ASP.NET Core». , , , , . , API . -API ASP.NET Core 2.1 .

GitHub .

-API ASP.NET Core

.NET ASP.NET Core. ASP.NET Core — -, , ASP.NET 1.0. , ASP.NET Core 2.1 - .

?

, . ( -). — « , , , .» : , , . , , . :

[Fact]
public async Task AlbumGetAllAsync()
{
    // Arrange

    // Act
    var albums = await _repo.GetAllAsync();

    // Assert
    Assert.Single(albums);
}

. — Arrange , , . , Arrange ( ). , Act, — , . Album, , . (Assert) . , .

xUnit. xUnit — .NET Framework .NET Core. xUnit .NET Core, .NET Core 2.1 SDK. Unit Test cli .NET Core dotnet test, xUnit Test IDE, Visual Studio 2017, Visual Studio Code JetBrain's Rider.

Figure 1: Creating a New Unit Test Project in Visual Studio 2017
1: Unit Test Visual Studio 2017

-API ASP.NET Core.

-API?

API . , . , , . ? , 100%- . , , API , , ? ! , .

Chinook.API , ( ), , Domain Data  . , ( ). ,   Domain Data , , . , , « ».

/ ?

, . , -API ASP.NET Core. API. , . , . , , . , Chinook.Domain (Album) ID 42, , , , (Artist). , , , .

«» (mocks ) . , , «» . , , . , .

, , , Unit Test . Chinook.MockData ( ). MockData Chinook.Data. , . , MockData (Dependency Injection — DI), Chinook.Domain , Chinook.Data, . . Data - .

: -API?

, -API ASP.NET Core, . , . , API , .

, API HTTP- . , API HTTP . API API Domain , , Data ( ).

- . xUnit . , xUnit Chinook.IntegrationTest, NuGet. Microsoft.AspNetCore.TestHost Chinook.IntegrationTest. , .

Figure 2: Adding NuGet Package Microsoft.AspNetCore.TestHost
2: NuGet Microsoft.AspNetCore.TestHost

API.

API , API, . (Entity) API. «Album».

API AlbumAPITest.cs. .

using Xunit;
using Chinook.API;
using Microsoft.AspNetCore.TestHost;
using Microsoft.AspNetCore.Hosting;
Figure 3: Integration test using directives
3:

TestServer HttpClient. _client HttpClient, TestServer, AlbumAPITest. TestServer — -, Startup Chinook.API . Development. -, API, , , API TestServer. .

Figure 4: Our first integration test to get all albums
4:

, 4 . AlbumGetAllTestAsync , API . , , Arrange/Act/Assert. HttpRequestMessage HTTP-, InlineData, URI, («/api/Album/»). _client HttpClient HTTP-, , , , HTTP- , — 200 OK. 4 API. , , HTTP-.

response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);

, API. InlineData, AlbumGetTestAsync. , , URI HttpRequestMessage. 5.

Figure 5: Second Integration Test for the Album Entity
5: Album

, , Test Runner , . DevOps (Continuous Integration - CI) — API . , , , API , , API .

Figure 6: Running Integration Tests in Visual Studio 2017
6: Visual Studio 2017

, , API, , -API ASP.NET Core.


"C# ASP.NET Core ". " GraphQL API ASP.NET Core" .




All Articles