Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 931
Razack Avatar asked Nov 27 '12 07:11

Razack


1 Answers

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;
like image 96
testCoder Avatar answered Oct 04 '22 18:10

testCoder