title: Integration Testing multipart/form-data c#
body: <p>I have trouble trying to create an integration test for my post call that accepts a viewmodel that has amongst other values, an IFormFile, which makes this call from an application/json to a multipart/form-data</p>
  <p>My IntegrationSetup class</p>
  <pre><code>protected static IFormFile GetFormFile()
          {
              byte[] bytes = Encoding.UTF8.GetBytes(&quot;test;test;&quot;);
  
              var file = new FormFile(
                  baseStream: new MemoryStream(bytes),
                  baseStreamOffset: 0,
                  length: bytes.Length,
                  name: &quot;Data&quot;,
                  fileName: &quot;dummy.csv&quot;
              )
              {
                  Headers = new HeaderDictionary(),
                  ContentType = &quot;text/csv&quot;
              };
  
              return file;
          } 
  </code></pre>
  <p>My Test Method</p>
  <pre><code>public async Task CreateAsync_ShouldReturnId()
          {
              //Arrange
              using var content = new MultipartFormDataContent();
              var stringContent = new StringContent(
                  JsonConvert.SerializeObject(new CreateArticleViewmodel
                  {
                      Title = &quot;viewModel.Title&quot;,
                      SmallParagraph = &quot;viewModel.SmallParagraph&quot;,
                      Url = &quot;viewModel.Url&quot;,
                      Image = GetFormFile()
                  }),
                  Encoding.UTF8,
                  &quot;application/json&quot;);
              stringContent.Headers.Add(&quot;Content-Disposition&quot;, &quot;form-data; name=\&quot;json\&quot;&quot;);
              content.Add(stringContent, &quot;json&quot;);
  
              //Act
              var response = await httpClient.PostAsync($&quot;{Url}&quot;, content);
              //Assert
              response.StatusCode.ShouldBe(HttpStatusCode.OK);
              int id = int.Parse(await response.Content.ReadAsStringAsync());
              id.ShouldBeGreaterThan(0);
          }
  </code></pre>
  <p>My Controller Method</p>
  <pre><code>[HttpPost]
          public async Task&lt;IActionResult&gt; CreateArticleAsync([FromForm] CreateArticleViewmodel viewModel)
          {
  
              var id = await _service.CreateAsync(viewModel).ConfigureAwait(false);
              if (id &gt; 0)
                  return Ok(id);
              return BadRequest();
          }
  </code></pre>
  <p>It throws a BadRequest without getting inside the method.</p>