简体   繁体   English

使用TestServer处理错误情况

[英]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.

相关问题 将CefSharp与Owin TestServer一起使用 - Using CefSharp with Owin TestServer 如何使用TestServer和Antiforgery修复POST集成测试中的500 Internal Server Error? ASP.NET核心 - How to fix 500 Internal Server Error for POST integration tests using TestServer and Antiforgery? ASP.NET Core 如何使用 WebApplicationFactory 在 TestServer 中切换服务? - How to switch services in TestServer using WebApplicationFactory? 为什么 TestServer (AspNetCore) 在静态文件上给出 404 错误? - Why the TestServer (AspNetCore) gives 404 error on static files? 使用 .NET Core 3.1 中的 TestServer 加载额外的 controller Web ZDB974238714CA8DE634A7CE1D0Z - Load additional controller using TestServer in .NET Core 3.1 Web API 使用Asp.NetCore TestServer托管的WebAPI的HttpClient连接问题 - HttpClient connection issue to WebAPI hosted using Asp.NetCore TestServer 在多种情况下使用一种方法 - Using one method for multiple scenarios 创建一个TestServer并将依赖注入与XUnit和ASP.NET Core 1.0一起使用 - Creating a TestServer and using Dependency Injection with XUnit and ASP.NET Core 1.0 在不使用Microsoft.AspNetCore.TestHost中包含的TestServer的情况下运行Kestrel进行测试 - Running Kestrel for testing without using the TestServer included in Microsoft.AspNetCore.TestHost 如何使用TestServer和数据种子类在内存数据库中共享以在内存中运行集成测试 - How to share in memory database using TestServer and data seeding class to run Integration Tests in memory
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM