title: How to do an integration test on my Asp.Net core web api endpoint where I upload a file?
body: <p>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!</p>
  
  <p>I am using <code>IFormFile</code> in my controller to receive the request, but I am getting a 400 Bad request because apparently my file is null. </p>
  
  <p>How do I allow an integration test to send a file to my endpoint? I found <a href="https://stackoverflow.com/questions/36858542/how-to-mock-an-iformfile-for-a-unit-integration-test-in-asp-net-core-1-mvc-6">this post</a> but that only talks about mocking <code>IFormFile</code>, not an integration test.</p>
  
  <hr>
  
  <p>My controller:</p>
  
  <pre><code>[HttpPost]
  public async Task&lt;IActionResult&gt; 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 };
  }
  </code></pre>
  
  <p>My integration test: </p>
  
  <pre><code>public class IntegrationTest:
      IClassFixture&lt;CustomWebApplicationFactory&lt;Startup&gt;&gt;
  {
      private readonly CustomWebApplicationFactory&lt;Startup&gt; _factory;
  
      public IntegrationTest(CustomWebApplicationFactory&lt;Startup&gt; 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());
      }
  </code></pre>
  
  <p>I hope you guys can help me (and possibly others!) out here! </p>