无法使用 Xunit 测试端点 - 状态代码:400,原因短语:'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:FilesNRIC.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);
}
}

最新更新