首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Request.GetOwinContext在单元测试中返回null -如何在单元测试中测试OWIN身份验证?

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

Stack Overflow用户
提问于 2014-07-19 12:46:35
回答 6查看 19K关注 0票数 20

我目前正在尝试使用OWIN对我正在编写的一个新WebAPI项目的身份验证进行单元测试,但在单元测试上下文中运行它时遇到了问题。

这是我的测试方法:

代码语言:javascript
复制
[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);
    }
}

我在获取.Result时得到了一个AggregateException,但有以下内部异常:

代码语言:javascript
复制
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()
...

我已经通过调试确认正在调用我的Startup方法,即调用ConfigurAuth

代码语言:javascript
复制
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);
}

我已经尝试了一些方法,但似乎都不起作用--我永远不能得到一个OWIN上下文。在以下代码上测试失败:

代码语言:javascript
复制
// 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();
}

这将调用UserManager属性:

代码语言:javascript
复制
public ApplicationUserManager UserManager
{
    get
    {
        return _userManager ?? Request.GetOwinContext()
           .GetUserManager<ApplicationUserManager>();
    }
    private set
    {
        _userManager = value;
    }
}

它在以下情况下失败:

代码语言:javascript
复制
return _userManager ?? Request.GetOwinContext()
    .GetUserManager<ApplicationUserManager>();

使用NullReferenceException - Request.GetOwinContext返回null

所以我的问题是:我是不是做错了?我应该只测试JSON响应吗?或者有没有一种“内部”测试OWIN身份验证的好方法?

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24836845

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档