Mock authenticated user using Moq in unit testing

10,564

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;
Share:
10,564
Razack
Author by

Razack

6 years of experience in designing and developing web based application using various latest technologies from Microsoft and other popular vendors. • Strong experience in Microsoft technologies like .Net 4 and 4.5, C#, ASP.Net MVC4, Entity Framework, Linq, ADO.Net ,Web API ,SQL Server,T-SQL and SSRS. • Strong experience in web technologies like HTML5, Javascript, Ajax, XML, CSS3 ,JSON, Kendo UI and Razor etc. • Working experience in open source frameworks and libraries used in web and multi-platform mobile development like jQuery, jQuery Templates, Handlebar JS, Angular JS, PhoneGap and Twitter Bootstrap. • Highly adaptable in quickly changing technologies and loving to works with latest client side libraries or frameworks and multi-platform mobile app development using HTML5 and Javascript.

Updated on June 04, 2022

Comments

  • Razack
    Razack almost 2 years

    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

  • Jezer
    Jezer almost 9 years
    I do that in a similar way, just without mocking IPrincipal: contollerContext.Setup(ctx => ctx.HttpContext.User.IsInRole("Administrator")).Returns(true‌​);