I am writing an integration test that tests the upload of a file to one of my endpoints and checks if the request result is correct!
I am using IFormFile in my controller to receive the request, but I am getting a 400 Bad request because apparently my file is null. 
How do I allow an integration test to send a file to my endpoint? I found this post but that only talks about mocking IFormFile, not an integration test.
My controller:
[HttpPost]
public async Task<IActionResult> AddFile(IFormFile file)
{
   if (file== null)
   {
       return StatusCode(400, "A file must be supplied");
   }
   // ... code that does stuff with the file..
   return CreatedAtAction("downloadFile", new { id = MADE_UP_ID }, { MADE_UP_ID };
}
My integration test:
public class IntegrationTest:
    IClassFixture<CustomWebApplicationFactory<Startup>>
{
    private readonly CustomWebApplicationFactory<Startup> _factory;
    public IntegrationTest(CustomWebApplicationFactory<Startup> factory)
    {
        _factory = factory;
    }
    [Fact]
    public async Task UploadFileTest()
    {
        // Arrange
        var expectedContent = "1";
        var expectedContentType = "application/json; charset=utf-8";
        var url = "api/bijlages";
        var client = _factory.CreateClient();
        // Act
        var file = System.IO.File.OpenRead(@"C:\file.pdf");
        HttpContent fileStreamContent = new StreamContent(file);
        var formData = new MultipartFormDataContent
        {
            { fileStreamContent, "file.pdf", "file.pdf" }
        };
        var response = await client.PostAsync(url, formData);
        fileStreamContent.Dispose();
        formData.Dispose();
        response.EnsureSuccessStatusCode();
        var responseString = await response.Content.ReadAsStringAsync();
        // Assert
        Assert.NotEmpty(responseString);
        Assert.Equal(expectedContent, responseString);
        Assert.Equal(expectedContentType, response.Content.Headers.ContentType.ToString());
    }
I hope you guys can help me (and possibly others!) out here!
Your code looks correct except the key in MultipartFormDataContent should be file & not file.pdf
Change the formdata to { fileStreamContent, "file", "file.pdf" }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With