2017-11-13 3 views
0

I WebAPI einfachen NUnit-TestTesting Filter mit IDependencyScope in Web API

[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") 
    }}}; 
} 

und in TestAuthenticationAttribute hat ich habe

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

Wie IExternalService Abhängigkeit im Test setzen/lösen? Brauche ich z.B. UnityContainer oder ich kann es ohne Container machen?

Antwort

0

Ich habe HttpConfiguration zu meinem HttpActionContext hinzugefügt, und jetzt wirft Context.Request.GetDependencyScope() keine System.NullReferenceException. Von cource ontext.Request.GetDependencyScope(). GetService (typeof (IExternalService)) ist null, aber jetzt ist es in Ordnung für meine Tests.

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; 

} 

Wenn ich Abhängigkeit lösen will, kann ich DependencyResolver meine Config hinzufügen oder Mockframework

Verwandte Themen