在Web API中使用IDependencyScope测试过滤器

时间:2017-11-13 15:55:05

标签: unit-testing owin webapi2

我有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或我可以不用容器吗?

1 个答案:

答案 0 :(得分:1)

我在我的HttpActionContext中添加了HttpConfiguration,现在Context.Request.GetDependencyScope()不会抛出System.NullReferenceException。 cource ontext.Request.GetDependencyScope()。GetService(typeof(IExternalService))为null,但现在我的测试没问题。

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框架