FormsAuthentication.SetAuthCookie mocking using Moq

余生长醉 提交于 2019-12-05 03:23:40

Inject IFormsAuthenticationService as a dependency to your LogOnController like this

private IFormsAuthenticationService formsAuthenticationService;
public LogOnController() : this(new FormsAuthenticationService())
{
}

public LogOnController(IFormsAuthenticationService formsAuthenticationService) : this(new FormsAuthenticationService())
{
    this.formsAuthenticationService = formsAuthenticationService;
}

The first constructor is for the framework so that the correct instance of IFormsAuthenticationService is used at runtime.

Now in your tests create an instance of LogonController using the other constructor by passing mock as below

var mockformsAuthenticationService = new Mock<IFormsAuthenticationService>();
//Setup your mock here

Change your action code to use the private field formsAuthenticationService as below

[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl = "")
{
    formsAuthenticationService.SignIn(model.UserName, model.RememberMe);
}

Hope this helps. I have left out the mock setup for you. Let me know if you are not sure how to set that up.

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