Reputation: 4543
I am writing xunit test to test this endpoint.
[Route("Document")]
[HttpPost]
public async Task<IActionResult> UploadFileAsync([FromForm] DocumentUploadDto documentUploadDto)
{
// code removed for brevity
}
When I put a breakpoint in this method, it doesn't reach here.
This is my code in 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);
}
}
}
In response
, I am getting StatusCode: 400, ReasonPhrase: 'Bad Request'
This is 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; }
}
Upvotes: 2
Views: 607
Reputation: 101583
You are sending JSON request (content type application/json
) but server expects form data. You need to use multipart form like this:
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);
}
}
Upvotes: 4