10

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

J. Steen
  • 15,470
  • 15
  • 56
  • 63
Razack
  • 950
  • 3
  • 13
  • 26
  • 2
    Just idle curiosity - have you tried anything yourself before you asked here? What didn't work for you? – J. Steen Nov 27 '12 at 08:19
  • 1
    Maybe [similar SO topic](http://stackoverflow.com/questions/3027264/mocking-user-identity-in-asp-net-mvc) could help? – alex.b Nov 27 '12 at 08:28
  • 1
    Wehey. Just like I'd have solved it too. Bottom line is, look into topics like dependency injection and inversion of control. – J. Steen Nov 27 '12 at 08:32

1 Answers1

22

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;
testCoder
  • 7,155
  • 13
  • 56
  • 75
  • I do that in a similar way, just without mocking `IPrincipal`: `contollerContext.Setup(ctx => ctx.HttpContext.User.IsInRole("Administrator")).Returns(true);` – Vitali Climenco Jun 19 '15 at 08:10
  • Dotnetcore: For me this ans not working. Pls ref. https://stackoverflow.com/a/58394501/672891 – Rikin Patel Apr 27 '23 at 11:16