在单元测试中使用模拟Moq的身份验证的用户 [英] Mock authenticated user using Moq in unit testing

查看:95
本文介绍了在单元测试中使用模拟Moq的身份验证的用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们如何使用起订量框架嘲笑身份验证的用户。窗体身份验证使用。

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);
}

我要在这里为模拟用户ID值

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;

这篇关于在单元测试中使用模拟Moq的身份验证的用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆