Test des API Web ASP.NET Core

Bonjour, Khabrovites! Pour les futurs Ă©tudiants du cours "DĂ©veloppeur C # ASP.NET Core", nous publions la traduction d'un article utile.


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: création d'un nouveau projet de test unitaire dans 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: Ajout du package NuGet 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: Test d'intégration à l'aide de directives
3:

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

 4:
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.

 5:      Album
5: Album

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

 6:     Visual Studio 2017
6: Visual Studio 2017

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


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




All Articles