【问题标题】:Testing filters with IDependencyScope in Web API在 Web API 中使用 IDependencyScope 测试过滤器
【发布时间】:2017-11-13 15:55:04
【问题描述】:

我有 WebApi 简单的 NUnit 测试

[Test]
public async Task Test()
{
    var attribute = new TestAuthenticationAttribute {ApiVersions = new[] {"v1"}};
    System.Web.Http.Controllers.HttpActionContext context = CreateExecutingContext();

    var executedContext = new HttpAuthenticationContext(context, null);

    const string reasonPhrase = "ReasonPhrase";
    const string messagePhrase = "MessagePhrase";

    executedContext.ErrorResult = new AuthenticationFailureResult(reasonPhrase, messagePhrase, executedContext.Request);

    await attribute.AuthenticateAsync(executedContext, CancellationToken.None);

    var errorResult = await executedContext.ErrorResult.ExecuteAsync(new CancellationToken());

    Assert.AreEqual(HttpStatusCode.Unauthorized, errorResult.StatusCode);
}

private System.Web.Http.Controllers.HttpActionContext CreateExecutingContext()
{
    return new System.Web.Http.Controllers.HttpActionContext { ControllerContext = new HttpControllerContext {Request = new HttpRequestMessage()
    {
         RequestUri = new Uri("http://TestApi/api/v1/Test")
    }}};
}

在 TestAuthenticationAttribute 我有

if (context.Request.GetDependencyScope().GetService(typeof(IExternalService)) is IExternalService externalService)
            Do some actions;

如何在测试中设置/解决 IExternalService 依赖?我需要吗? UnityContainer 还是我可以不用容器?

【问题讨论】:

    标签: unit-testing owin webapi2


    【解决方案1】:

    我将 HttpConfiguration 添加到我的 HttpActionContext 中,现在 Context.Request.GetDependencyScope() 不会抛出 System.NullReferenceException。当然 ontext.Request.GetDependencyScope().GetService(typeof(IExternalService)) 为空,但现在我的测试可以了。

    private System.Web.Http.Controllers.HttpActionContext CreateExecutingContext()
    {
        var config = new HttpConfiguration();
    
        var httpActionContext =  new System.Web.Http.Controllers.HttpActionContext
        {
            ControllerContext = new HttpControllerContext
            {
                Request = new HttpRequestMessage()
                {
                    RequestUri = new Uri("http://TestApi/api/v1/Test"),
                },
    
                Configuration = config
            }
        };
    
        httpActionContext.ControllerContext.Request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;
    
        return httpActionContext;
    
    }
    

    如果我想解决依赖关系,我可以将 DependencyResolver 添加到我的配置或 Mocking 框架中

    【讨论】:

    • 非常感谢,它帮助我摆脱了困境
    猜你喜欢
    • 1970-01-01
    • 2018-01-19
    • 2012-08-04
    • 2013-01-05
    • 2021-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-05
    相关资源
    最近更新 更多