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

标签 c# xunit

我正在编写 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);
        }
    }
}        

响应中,我收到 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);
    }
}

关于c# - 无法使用 Xunit 测试端点 - StatusCode : 400, ReasonPhrase: 'Bad Request',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69873697/

相关文章:

c# - xUnit 的模拟服务

c# - 实现 C# 控制台应用程序的正确方法?

c# - 如何在 WinForms 中删除一个 DateTimePicker 实例?

C# Stryker 突变框架

c# - Xunit 2.3.0 无法将日期作为内联参数传递

f# - 是否可以在无需将测试代码标记为内部的情况下测试内部代码?

c# - 防止多线程中的不良优化

c# - 如何实现定义另一个接口(interface)元素的接口(interface)

c# - 如何将其他参数传递给 OWIN 登录?

jenkins - xUnit 在 Jenkins 下失败 : BadImageFormatException