测试ASP.NET Core Web API

您好,Khabrovites!对于将来学习“ C#ASP.NET Core Developer”课程的学生,我们发布了一篇有用的文章的翻译。


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.

图1:在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. , .

图2:添加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;
图3:使用指令的集成测试
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:相册实体的第二次集成测试
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