Razack
Razack

Reputation: 950

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

Upvotes: 10

Views: 12063

Answers (1)

testCoder
testCoder

Reputation: 7385

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;

Upvotes: 22

Related Questions