ASP.NET集成测试-TestHost始终返回500内部服务器错误

时间:2019-05-10 18:15:52

标签: asp.net asp.net-core asp.net-core-2.0 xunit.net asp.net-core-testhost

我目前正在使用xUnit编写集成测试,因此我只尝试为AuthController编写一个测试以检查身份验证是否有效(顺便说一句。我只想进行测试)。

我不知道自己在设置什么错误,但是每次运行测试时,都会收到500 Internal Server错误:

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).

我的测试如下:

[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();
    }
}

我什至都不知道该如何调试...我在Visual Studio代码调试器中看到的只是500响应。暂停

编辑: 这是我要测试的控制器动作:

[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)
         });
}

我尝试将控制器修改为始终返回Ok Http响应,但是在测试中,我仍然收到500个内部服务器错误。

1 个答案:

答案 0 :(得分:0)

问题很简单,我是一个哑巴,我试图将请求发布到/api/authenticate而不是/api/auth/authenticate