【发布时间】:2014-09-10 06:58:37
【问题描述】:
我目前正在尝试对我正在编写的使用 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);
}
}
我在获得.Result 时收到AggregateException,但内部异常如下:
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:
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 上下文。以下代码测试失败:
// 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 属性:
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? Request.GetOwinContext()
.GetUserManager<ApplicationUserManager>();
}
private set
{
_userManager = value;
}
}
它失败了:
return _userManager ?? Request.GetOwinContext()
.GetUserManager<ApplicationUserManager>();
NullReferenceException - Request.GetOwinContext 正在返回 null。
所以我的问题是:我是不是搞错了?我应该只测试 JSON 响应吗?或者有没有“内部”测试 OWIN 身份验证的好方法?
【问题讨论】:
-
为文字墙道歉 - 我想提供尽可能多的上下文。 :)
-
可惜没有一个答案是实际答案,而不是解决方法
-
确实如此。我不想嘲笑它,我想实际测试它。哦,好吧。
标签: asp.net-mvc unit-testing authentication asp.net-web-api owin