我有 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")
}}};
}
在测试身份验证属性我有
if (context.Request.GetDependencyScope().GetService(typeof(IExternalService)) is IExternalService externalService)
Do some actions;
如何在测试中设置/解决IExternalService依赖关系?我是否需要例如 UnityContainer,或者我可以在没有容器的情况下完成?
我将 HttpConfiguration 添加到我的 HttpActionContext 中,现在 Context.Request.GetDependencyScope(( 不会抛出 System.NullReferenceException。的文字。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;
}
如果我想解决依赖关系,我可以将依赖解析器添加到我的配置或模拟框架中