asp.net-mvc – Request.GetOwinContext在单元测试中返回null – 如何在单元测试中测
发布时间:2020-05-23 18:33:06 所属栏目:asp.Net 来源:互联网
导读:我正在尝试单元测试我正在使用OWIN进行身份验证的新WebAPI项目的身份验证,并且我在单元测试上下文中运行它时遇到问题。 这是我的测试方法: [TestMethod]public void TestRegister(){ using (WebApp.StartStartup(localhost/myAPI)) using (AccountControlle
|
我正在尝试单元测试我正在使用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);
}
}
我得到一个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()
...
我已经通过调试确认我的启动方法正在被调用,调用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认证? 解决方法GetOwinContext调用context.GetOwinEnvironment();这是 private static IDictionary<string,object> GetOwinEnvironment(this HttpContextBase context)
{
return (IDictionary<string,object>) context.Items[HttpContextItemKeys.OwinEnvironmentKey];
}
和HttpContextItemKeys.OwinEnvironmentKey是一个常量“owin.Environment” 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; (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- asp.net – DotLess的“web”属性究竟做了什么?
- 在Azure网络应用程序中显示ASP.NET 5错误页面
- asp.net-mvc – ASP.Net MVC 2验证是否需要更多的思考在模式
- asp.net – 如何使用ValueInjector映射列表
- asp.net读取磁盘文件、删除实例代码
- asp.net-mvc – 我应该把我的控制器业务逻辑放在MVC3中
- ASP.NET等价的服务器端包括
- asp.net – 用于分析在azure上运行的网站性能的步骤
- asp.net-mvc – ASP.NET MVC FileStreamResult不能按预期工
- asp.net – 在IHTTPHandler中以编程方式创建System.Web.UI.
推荐文章
站长推荐
- asp.net-mvc – 在ASP.NET MVC中的JSON属性中返回
- 我可以使用ASP.NET Core仅针对.NET 4.6.1吗?
- asp.net-mvc – 属性级验证错误阻碍了类级验证的
- asp.net – 元素 system.webServer’有无效的chi
- ASP.NET控件属性与[Flags]枚举
- asp.net – 所有PartialView的自定义ActionResul
- asp.net-mvc – 依赖注入和ASP.Net成员提供程序
- asp.net-web-api – 默认请求标头不接受任何值,它
- asp.net-mvc-3 – 自定义成员资格提供程序和统一
- asp.net – Windows Azure VM网站设置
热点阅读
