无法使用 Xunit 测试端点 - StatusCode:400,ReasonPhrase:'Bad Request'

Unable to test endpoint with Xunit - StatusCode: 400, ReasonPhrase: 'Bad Request'

我正在编写 xunit 测试来测试这个端点。

[Route("Document")]
[HttpPost]
public async Task<IActionResult> UploadFileAsync([FromForm] DocumentUploadDto documentUploadDto)
{
   // code removed for brevity
}

当我在这个方法中设置断点时,它没有到达这里。

这是我在 XUnit 中的代码

[Fact]
public async Task When_DocumentTypeInvalidFileType_Then_ShouldFail()
{
    using (var client = new HttpClient() { BaseAddress = new Uri(TestSettings.BaseAddress) })
    {
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _authToken);

        var filePath = @"D:\Files\NRIC.pdf";

        using (var stream = File.OpenRead(filePath))
        {
            FormFile formFile = new FormFile(stream, 0, stream.Length, null, Path.GetFileName(stream.Name))
            {
                Headers = new HeaderDictionary(),
                ContentType = "application/pdf"
            };

            var documentUploadDto = new DocumentUploadDto
            {
                DocumentType = ApplicationDocumentType.ICFRONT,
                DraftId = Guid.NewGuid(),
                File = formFile
            };
            var encodedContent = new StringContent(JsonConvert.SerializeObject(documentUploadDto), Encoding.UTF8, "application/json");

            // Act                
            var response = await client.PostAsync("/ABC/Document", encodedContent);
            var responseString = await response.Content.ReadAsStringAsync();
            _output.WriteLine("response: {0}", responseString);
        }
    }
}        

response 中,我得到 StatusCode:400,ReasonPhrase:'Bad Request'

这是DocumentUploadDto

public class DocumentUploadDto
{
    [FileValidation]
    public IFormFile File { get; set; }
    public ApplicationDocumentType DocumentType { get; set; }
    public Guid DraftId { get; set; }
    public Guid Id { get; set; }
}

您正在发送 JSON 请求(内容类型 application/json),但服务器需要表单数据。您需要像这样使用多部分形式:

using (var stream = File.OpenRead(filePath)) {
    using (var form = new MultipartFormDataContent()) {
        // metadata from your DocumentUploadDto
        form.Add(new StringContent(ApplicationDocumentType.ICFRONT.ToString()), "DocumentType");
        form.Add(new StringContent(Guid.NewGuid().ToString()), "DraftId");
        form.Add(new StringContent(Guid.NewGuid().ToString()), "Id");
        // here is the file
        var file = new StreamContent(stream);
        // set Content-Type
        file.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/pdf");
        form.Add(file, "File", Path.GetFileName(filePath));

        // Act                
        var response = await client.PostAsync("/ABC/Document", form);
        response.EnsureSuccessStatusCode();
        var responseString = await response.Content.ReadAsStringAsync();
        _output.WriteLine("response: {0}", responseString);
    }
}