I am currently using xUnit to write integration tests and so fast I only attempted to write a single test for my AuthController to check if the authentication works (It works btw. I just want to have tests).
I do not know what I am setting up wrong but every time I run my test I get a 500 Internal Server error:
Failed AuthControllerIntegrationTests.CanLogin
Error Message:
System.Net.Http.HttpRequestException : Response status code does not indicate success: 500 (Internal Server Error).
[xUnit.net 00:00:02.19] AuthControllerIntegrationTests.CanLogin [FAIL]
Failed AuthControllerIntegrationTests.CanLogin
Error Message:
System.Net.Http.HttpRequestException : Response status code does not indicate success: 500 (Internal Server Error).
My test looks like this:
[Fact]
public async Task CanLogin()
{
var webHostBuilder =
new WebHostBuilder()
.UseEnvironment("Development")
.UseConfiguration(new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build())
.UseStartup<Startup>();
using (var server = new TestServer(webHostBuilder))
using (var client = server.CreateClient())
{
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
object password = new {
password = "password"
};
var httpResponse = await client.PostAsJsonAsync("/api/authenticate", password);
httpResponse.EnsureSuccessStatusCode();
}
}
I dont even know how to debug this...all I see in visual studio code debugger is the 500 response. Halp
EDIT: Here is the controller action that I would like to test:
[AllowAnonymous]
[HttpPost("authenticate")]
public IActionResult Authenticate([FromBody]AuthDTO input)
{
var token = _authService.Authenticate(input.Password);
if (token == null)
return BadRequest(new { message = "Incorrect password!" });
return Ok(new
{
token = new JwtSecurityTokenHandler().WriteToken(token)
});
}
I've tried modifying the controller to always return an Ok Http response, but in the test I still got a 500 internal server error.
The problem was simply that I am a dum-dum, and I was trying to post the request to
/api/authenticateinstead of/api/auth/authenticate