deh*_*eha 9 c# integration-testing xunit.net asp.net-core
我正在开发一个 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();
}
}
Run Code Online (Sandbox Code Playgroud)
当我从这个装置中使用 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!");
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在你可以在你的 Startup.cs 中注册这个中间件:
...
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseMiddleware<ExceptionMiddleware>();
...
app.UseMvc();
}
Run Code Online (Sandbox Code Playgroud)
如果你不想一直使用它,你可以创建TestStartup- 你的Startup和覆盖Configure方法的子类UseMiddleware只在那里调用。然后您只需要TestStartup在测试中使用新类。
| 归档时间: |
|
| 查看次数: |
984 次 |
| 最近记录: |