[英]Using TestServer for error scenarios
I am trying to use TestServer
to verify how my application would behave if an exception. 我试图使用TestServer
来验证我的应用程序在出现异常时的行为。 For example, in this sample I have a controller will call to a database but in my test I am deliberately setting up the repository
to throw an exception. 例如,在此示例中,我有一个控制器将调用数据库,但是在我的测试中,我故意设置repository
以引发异常。
[Route("api/[controller]")]
public class ValuesController : Controller
{
private readonly IRepository _repo;
public ValuesController(IRepository repo)
{
_repo = repo;
}
// GET api/values
[HttpGet]
public IEnumerable<string> Get()
{
this._repo.Execute();
return new string[] { "value1", "value2" };
}
}
I am expecting an internal server error to be returned. 我期望将返回内部服务器错误。 Although this works if were to F5 and run the application I was hoping to do this via TestServer
. 尽管这对于F5并运行应用程序来说是可行的,但我还是希望通过TestServer
做到这一点。
[Fact]
public void Test1()
{
using (var client = new TestServer(new WebHostBuilder()
.UseStartup<TestStartup>())
.CreateClient())
{
var result = client.GetAsync("api/values").Result;
Assert.Equal(result.StatusCode, HttpStatusCode.InternalServerError);
}
}
public class TestStartup : Startup
{
protected override void ConfigureDependencies(IServiceCollection services)
{
services.AddSingleton<IRepository, FailingRepo>();
}
}
}
public class FailingRepo : IRepository
{
public void Execute()
{
throw new NotImplementedException();
}
}
Instead what I get is the test failing for: 相反,我得到的是测试失败:
System.AggregateException : One or more errors occurred. System.AggregateException:发生一个或多个错误。 (The method or operation is not implemented.) (该方法或操作未实现。)
I can get this to work if I was to plug in some custom middleware at the start of the pipeline, something similar to this: 如果我要在管道开始时插入一些自定义中间件,则可以使它工作,类似于以下内容:
public class ErrorMiddleware
{
private RequestDelegate next;
private readonly ILogger logger;
public ErrorMiddleware(RequestDelegate next, ILogger logger)
{
this.next = next;
this.logger = logger;
}
public async Task Invoke(HttpContext context)
{
try
{
await this.next.Invoke(context);
}
catch (Exception e)
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
}
}
}
I remember being able to do this via Owin Test Server available in the full .NET framework. 我记得可以通过完整.NET框架中可用的Owin Test Server来执行此操作。 Any ideas how to go about doing this? 任何想法如何去做呢?
You could use WebApplicationFactory : 您可以使用WebApplicationFactory :
public class BasicTests
: IClassFixture<WebApplicationFactory<RazorPagesProject.Startup>>
{
private readonly WebApplicationFactory<RazorPagesProject.Startup> _factory;
public BasicTests(WebApplicationFactory<RazorPagesProject.Startup> factory)
{
_factory = factory;
}
and instead of the generic type RazorPagesProject.Startup
use your own project to test. 而不是通用类型的RazorPagesProject.Startup
使用您自己的项目进行测试。 The factory will provide you the option to access to the routes you want and test they if they are perfoming as you want: 工厂将为您提供访问所需路线的选项,并测试它们是否如您所愿地进行测试:
// Arrange
var client = _factory.CreateClient();
// Act
var response = await client.GetAsync("api/Values");
//
response.EnsureSuccessStatusCode(); // Status Code 200-299
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.