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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With