Quantcast
Channel: Web API
Viewing all articles
Browse latest Browse all 4850

Testing filters with IDependencyScope in Web API

$
0
0

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?


Viewing all articles
Browse latest Browse all 4850

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>