2

为使用 User.Identity 的操作编写单元测试时,显示错误无法将“Castle.Proxies.IIdentityProxy”类型的对象转换为“MyApp.Web.Models.CurrentUser”类型。

当前用户类别:

[Serializable]
public class CurrentUser : IIdentity
{
    public CurrentUser (){}
    public CurrentUser (string name, string displayName, int userId)
    {
        this.Name = name;
        this.DisplayName = displayName;
        this.UserId = userId;
    }
    public CurrentUser (string name, string displayName, int userId,string roleName)
    {
        this.Name = name;
        this.DisplayName = displayName;
        this.UserId = userId;
        this.RoleName = roleName;
    }
    public CurrentUser (string name, UserInfo userInfo)
        : this(name, userInfo.DisplayName, userInfo.UserId,userInfo.RoleName)
    {
        if (userInfo == null) throw new ArgumentNullException("userInfo");
        this.UserId = userInfo.UserId;
    }

    public CurrentUser (FormsAuthenticationTicket ticket)
        : this(ticket.Name, UserInfo.FromString(ticket.UserData))
    {
        if (ticket == null) throw new ArgumentNullException("ticket");
    }

    public string Name { get; private set; }

    public string AuthenticationType
    {
        get { return "GoalSetterForms"; }
    }

    public bool IsAuthenticated
    {
        get { return true; }
    }

    public string DisplayName { get; private set; }
    public string RoleName { get; private set; }
    public int UserId { get; private set; }
}

控制器动作

public PartialViewResult SomeList()
{
    int userid = ((CurrentUser )(User.Identity)).UserId; //Error shows here

    var list= listService.GetLists(userid);
    return PartialView("ListView", list);
}

单元测试

[Test]
public void SomeList_Test()
{

    var controllerContext = new Mock<ControllerContext>();
    var principal = new Moq.Mock<IPrincipal>();

    ListController controller = new ListController (listService);

    principal.SetupGet(x => x.Identity.Name).Returns("abc");
    controllerContext.SetupGet(x => x.HttpContext.User).Returns(principal.Object);
    controllerContext.SetupGet(p =>      p.HttpContext.Request.IsAuthenticated).Returns(true);
    controller.ControllerContext = controllerContext.Object;

}

提前致谢, 拉扎克

4

1 回答 1

4

我只是遇到了同样的事情,但有点不同。

代替

principal.SetupGet(x => x.Identity.Name).Returns("abc");

principal.SetupGet(x => x.Identity).Returns(new CurrentUser("abc", "test", 123));
于 2012-12-14T20:14:19.390 回答