2

我有 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 或者我可以在没有容器的情况下完成它?

4

1 回答 1

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

于 2017-11-14T06:40:20.213 回答