我们有一个提供DELETE方法的.NET Core 3.1 API。
[HttpDelete("email")]
[Authorize]
[ProducesResponseType(StatusCodes.Status204NoContent)]
public async Task<IResponse> DeleteEmail([FromBody] EmailApiModel emailApiModel)
{
var loginEmail = this.User.FindFirst(ClaimTypes.Email).Value;
await this.userService.DeleteEmailAsync(loginEmail, emailApiModel.Email);
return await Task.FromResult(new Response((int)HttpStatusCode.NoContent));
}
EmailApiModel看起来像这样:
public class EmailApiModel
{
[Email]
[Required]
public string Email { get; set; } = string.Empty;
}
尝试为此方法编写集成测试时,我陷入困境。
集成测试方法如下:
[Fact]
public async Task DeleteEmail_WhenCalled_Then402IsReturnedAndEmailIsDeleted()
{
const string emailToDelete = "delete@email.com";
this.GivenUserWithLoginEmailAndAdditionalEmails(ValidUserMail, new [] { emailToDelete });
this.TheApplicationIsUpAndRunningWithFakedAuthentication();
var emailApiModel = new EmailApiModel { Email = emailToDelete };
var httpResponseMessage = await this.DeleteEmail(emailApiModel);
this.ThenTheResponseMessageShouldBe(httpResponseMessage, HttpStatusCode.OK);
this.ThenTheResponseShouldBe(httpResponseMessage, HttpStatusCode.NoContent);
}
protected async Task<HttpResponseMessage> DeleteEmail(EmailApiModel emailApiModel)
{
var jsonData = JsonSerializer.Serialize(emailApiModel);
var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
return await this.HttpClient.DeleteAsync(Api.User.Email, content);
}
HttpClient
是通过CustomWebApplicationFactory设置的
//https://docs.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-3.0
this.httpClient = this.WebApplicationFactory.CreateClient(new WebApplicationFactoryClientOptions {AllowAutoRedirect = false});
我遇到的问题是,HttpClient上的DeleteAsync
-Method不允许我提供内容(因此无法进行此调用:await this.HttpClient.DeleteAsync(Api.User.Email, content);
)
DeleteAsync-Method的唯一重载需要额外的CancellationToken。
如何在集成测试中提供内容?
预先感谢