无法将类型为“Castle.Proxies.IIdentityProxy”的对象强制转换为“MyApp.Web.Models.CurrentUser”。使用Moq和单元测试

时间:2012-11-28 05:20:12

标签: c# moq httpcontext

为使用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;

}

提前致谢, Razack

1 个答案:

答案 0 :(得分:3)

我刚遇到同样的事情,但有点不同。

替换

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

principal.SetupGet(x => x.Identity).Returns(new CurrentUser("abc", "test", 123));