Error in UnitTest for WebSecurity.Login simple membership

房东的猫 提交于 2019-12-08 12:30:59

问题


I am writing a unit test for login process and have used simple membership api. from web project, login is working fine, but while in unit test. simple membership api is raising exception.

API is throwing error on WebSecurity.Login method.

System.NullReferenceException was caught HResult=-2147467261 Message=Object reference not set to an instance of an object. Source=System.Web StackTrace: at System.Web.Security.FormsAuthentication.SetAuthCookie(String userName, Boolean createPersistentCookie, String strCookiePath) at System.Web.Security.FormsAuthentication.SetAuthCookie(String userName, Boolean createPersistentCookie) at WebMatrix.WebData.WebSecurity.Login(String userName, String password, Boolean persistCookie) at [ code ] InnerException:

WebSecurity.UserExists is working fine.

I think, error is due to 'cookies object is not available in unit test project'


回答1:


acually WebSecurity.Login uses FormsAuthentication.SetAuthCookie behind the scene, since FormsAuthentication.SetAuthCookie uses old httpcontext api therefore even with moq httpcontext it is throwing exception.

http://forums.asp.net/t/1871234.aspx

so solution is to dependency injection.

FormsAuthentication.SetAuthCookie mocking using Moq

http://forums.asp.net/post/5257516.aspx



来源:https://stackoverflow.com/questions/20739874/error-in-unittest-for-websecurity-login-simple-membership

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!