'Xunit integration test dotnet 6 System.Net.Http.HttpRequestException : Response status code does not indicate success: 415 (Unsupported Media Type)

Hello I'm learning integration testing and I want to test a 'POST' method from my controller using xunit and WebApplicationFactory But I'm getting this exception

Error Message: System.Net.Http.HttpRequestException : Response status code does not indicate success: 415 (Unsupported Media Type). Stack Trace: at System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()

This is my code for the test:

using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using Xunit;

namespace integrationtest.IntegrationTests;

public class ControllerTest  : IClassFixture<TestingWebAppFactory<Program>>
{
   private readonly HttpClient _client;
   public ControllerTest(TestingWebAppFactory<Program> factory) 
       => _client = factory.CreateClient();

   

   [Fact]
   public async Task AddInternshipMemberTest()
   {
       var postRequest = new HttpRequestMessage(HttpMethod.Post, "/api/InternshipMember/AddInternshipMember");

       var formModel = new Dictionary<string, string>
       {
           { "var1", "1"},
           { "var2", "0"},
           { "var3", "135"},
           { "var4", "1"},
           { "var5", "1"},
           { "var6", "1"},
           { "var7", "3" }
       };
       postRequest.Content = new FormUrlEncodedContent(formModel); 
       var response = await _client.SendAsync(postRequest); 
               
       response.EnsureSuccessStatusCode(); 
               
       var responseString = await response.Content.ReadAsStringAsync(); 
               
       Assert.Contains("1", responseString); 
   }
}

Can anyone help why i'm getting that error?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source