2

I have WebApi simple NUnit Test

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

and in TestAuthenticationAttribute I have

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

How to set/resolve IExternalService dependency in test? Do I need e.g. UnityContainer or I can do it without container?

1 Answers1

1

I added HttpConfiguration to my HttpActionContext and now Context.Request.GetDependencyScope() doesn't throw System.NullReferenceException. Of cource ontext.Request.GetDependencyScope().GetService(typeof(IExternalService)) is null, but now It's ok for my 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;

}

If I want to resolve dependency, I will can add DependencyResolver to my config or Mocking framework