简体   繁体   中英

Mock authenticated user using Moq in unit testing

How we can mock the authenticated user using Moq framework. Form Authentication used.

I need to write unit tests for the action below

public PartialViewResult MyGoals()
{
    int userid = ((SocialGoalUser)(User.Identity)).UserId;
    var Goals = goalService.GetMyGoals(userid);
    return PartialView("_MyGoalsView", Goals);
}

I need to mock the value for userid here

I have used something like that, maybe it helps you:

var controllerContext = new Mock<ControllerContext>();
var principal = new Moq.Mock<IPrincipal>();
principal.Setup(p => p.IsInRole("Administrator")).Returns(true);
principal.SetupGet(x => x.Identity.Name).Returns(userName);
controllerContext.SetupGet(x => x.HttpContext.User).Returns(principal.Object);
controller.ControllerContext = controllerContext.Object;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM