Request.GetOwinContext在单元测试中返回null - 如何在单元测试中测试OWIN身份验证?

Cod*_*man 19 authentication asp.net-mvc unit-testing asp.net-web-api owin

我目前正在尝试单独测试我正在使用OWIN进行身份验证的新WebAPI项目的身份验证,并且我在单元测试上下文中运行它时遇到问题.

这是我的测试方法:

[TestMethod]
public void TestRegister()
{
    using (WebApp.Start<Startup>("localhost/myAPI"))
    using (AccountController ac = new AccountController()
        {
            Request = new System.Net.Http.HttpRequestMessage
                (HttpMethod.Post, "http://localhost/myAPI/api/Account/Register")
        })
    {
        var result = ac.Register(new Models.RegisterBindingModel()
        {
            Email = "testemail@testemail.com",
            Password = "Pass@word1",
            ConfirmPassword = "Pass@word1"
        }).Result;
        Assert.IsNotNull(result);
    }
}
Run Code Online (Sandbox Code Playgroud)

我发现了一个AggregateException关于获得.Result具有以下内部异常:

Result Message: 
Test method myAPI.Tests.Controllers.AccountControllerTest.TestRegister 
    threw exception: 
System.ArgumentNullException: Value cannot be null.
Parameter name: context
Result StackTrace:  
at Microsoft.AspNet.Identity.Owin.OwinContextExtensions
    .GetUserManager[TManager](IOwinContext context)
at myAPI.Controllers.AccountController.get_UserManager()
...
Run Code Online (Sandbox Code Playgroud)

我通过调试确认我的Startup方法被调用,调用ConfigurAuth:

public void ConfigureAuth(IAppBuilder app)
{
    HttpConfiguration config = new HttpConfiguration();
    config.MapHttpAttributeRoutes();
    app.UseWebApi(config);

    // Configure the db context and user manager to use a single 
    //  instance per request
    app.CreatePerOwinContext(ApplicationDbContext.Create);
    app.CreatePerOwinContext<ApplicationUserManager>
        (ApplicationUserManager.Create);

    // Enable the application to use a cookie to store information for 
    //  the signed in user
    //  and to use a cookie to temporarily store information about a 
    //  user logging in with a third party login provider
    app.UseCookieAuthentication(new CookieAuthenticationOptions());
    app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

    // Configure the application for OAuth based flow
    PublicClientId = "self";
    OAuthOptions = new OAuthAuthorizationServerOptions
    {
        TokenEndpointPath = new PathString("/Token"),
        Provider = new ApplicationOAuthProvider(PublicClientId),
        AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
        AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
        AllowInsecureHttp = true
    };

    // Enable the application to use bearer tokens to authenticate users
    app.UseOAuthBearerTokens(OAuthOptions);
}
Run Code Online (Sandbox Code Playgroud)

我尝试了一些东西,但似乎没有任何工作 - 我永远无法获得OWIN背景.以下代码的测试失败:

// POST api/Account/Register
[AllowAnonymous]
[Route("Register")]
public async Task<IHttpActionResult> Register(RegisterBindingModel model)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    var user = new ApplicationUser() 
       { UserName = model.Email, Email = model.Email };

    IdentityResult result = await UserManager.CreateAsync(user, model.Password);

    if (!result.Succeeded)
    {
        return GetErrorResult(result);
    }

    return Ok();
}
Run Code Online (Sandbox Code Playgroud)

这称为UserManager财产:

public ApplicationUserManager UserManager
{
    get
    {
        return _userManager ?? Request.GetOwinContext()
           .GetUserManager<ApplicationUserManager>();
    }
    private set
    {
        _userManager = value;
    }
}
Run Code Online (Sandbox Code Playgroud)

它失败了:

return _userManager ?? Request.GetOwinContext()
    .GetUserManager<ApplicationUserManager>();
Run Code Online (Sandbox Code Playgroud)

NullReferenceException- Request.GetOwinContext正在回归null.

所以我的问题是:我接近这个错误吗?我应该只测试JSON响应吗?或者有一种"内部"测试OWIN身份验证的好方法吗?

Bir*_*rey 13

GetOwinContext调用context.GetOwinEnvironment(); 是的

  private static IDictionary<string, object> GetOwinEnvironment(this HttpContextBase context)
    {
        return (IDictionary<string, object>) context.Items[HttpContextItemKeys.OwinEnvironmentKey];
    }
Run Code Online (Sandbox Code Playgroud)

和HttpContextItemKeys.OwinEnvironmentKey是一个常量"owin.Environment"所以如果你在httpcontext的Items中添加它,它将起作用.

var request = new HttpRequest("", "http://google.com", "rUrl=http://www.google.com")
    {
        ContentEncoding = Encoding.UTF8  //UrlDecode needs this to be set
    };

    var ctx = new HttpContext(request, new HttpResponse(new StringWriter()));

    //Session need to be set
    var sessionContainer = new HttpSessionStateContainer("id", new SessionStateItemCollection(),
        new HttpStaticObjectsCollection(), 10, true,
        HttpCookieMode.AutoDetect,
        SessionStateMode.InProc, false);
    //this adds aspnet session
    ctx.Items["AspSession"] = typeof(HttpSessionState).GetConstructor(
        BindingFlags.NonPublic | BindingFlags.Instance,
        null, CallingConventions.Standard,
        new[] { typeof(HttpSessionStateContainer) },
        null)
        .Invoke(new object[] { sessionContainer });

    var data = new Dictionary<string, object>()
    {
        {"a", "b"} // fake whatever  you need here.
    };

    ctx.Items["owin.Environment"] = data;
Run Code Online (Sandbox Code Playgroud)


Gno*_*ian 9

为了确保在测试期间可以使用OWIN上下文(即,在调用时修复空引用异常Request.GetOwinContext()),您需要Microsoft.AspNet.WebApi.Owin在测试项目中安装NuGet包.安装完成后,您可以SetOwinContext在请求中使用扩展方法.

例:

var controller = new MyController();
controller.Request = new HttpRequestMessage(HttpMethod.Post,
    new Uri("api/data/validate", UriKind.Relative)
    );
controller.Request.SetOwinContext(new OwinContext());
Run Code Online (Sandbox Code Playgroud)

请参阅https://msdn.microsoft.com/en-us/library/system.net.http.owinhttprequestmessageextensions.setowincontext%28v=vs.118%29.aspx

话虽如此,我同意您的具体用例的其他答案 - 在构造函数中提供AppplicationUserManager实例或工厂.的SetOwinContext,如果你需要直接与您的测试将使用情境互动以上步骤是必要的.