我正在编写 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/