我正在开发一个 Web API,在某些情况下会响应 500(我知道设计很丑,但对此无能为力)。在测试中,有一个包含 AspNetCore.TestHost 的 ApiFixture:
public class ApiFixture
{
public TestServer ApiServer { get; }
public HttpClient HttpClient { get; }
public ApiFixture()
{
var config = new ConfigurationBuilder()
.AddEnvironmentVariables()
.Build();
var path = Assembly.GetAssembly(typeof(ApiFixture)).Location;
var hostBuilder = new WebHostBuilder()
.UseContentRoot(Path.GetDirectoryName(path))
.UseConfiguration(config)
.UseStartup<Startup>();
ApiServer = new TestServer(hostBuilder);
HttpClient = ApiServer.CreateClient();
}
}
当我从这个固定装置中使用 HttpClient 调用 API 端点时,它应该响应 500,而不是我收到在测试的控制器中引发的异常。我知道在测试中这可能是一个不错的功能,但我不希望这样 - 我想测试控制器的实际行为,它返回内部服务器错误。有没有办法重新配置 TestServer 以返回响应?
控制器操作中的代码无关紧要,可以是throw new Exception();
您可以创建一个异常处理中间件并在测试中使用它,或者更好的是始终使用它
public class ExceptionMiddleware
{
private readonly RequestDelegate next;
public ExceptionMiddleware(RequestDelegate next)
{
this.next = next;
}
public async Task Invoke(HttpContext httpContext)
{
try
{
await this.next(httpContext);
}
catch (Exception ex)
{
httpContext.Response.ContentType = MediaTypeNames.Text.Plain;
httpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
await httpContext.Response.WriteAsync("Internal server error!");
}
}
}
现在您可以在 Startup.cs 中注册此中间件:
...
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseMiddleware<ExceptionMiddleware>();
...
app.UseMvc();
}
如果您不想一直使用它,您可以创建TestStartup
- 你的一个子班Startup
并覆盖Configure
调用方法UseMiddleware
只有在那里。然后你需要使用新的TestStartup
仅在测试中上课。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)