title: Unable to cast object of type 'Castle.Proxies.IIdentityProxy' to type 'MyApp.Web.Models.CurrentUser'. using Moq and Unit test
body: <p>When writing a unit test for an action that uses User.Identity, shows an error <strong>Unable to cast object of type 'Castle.Proxies.IIdentityProxy' to type 'MyApp.Web.Models.CurrentUser'.</strong></p>
  
  <p><strong>Current user class :</strong></p>
  
  <pre><code>[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; }
  }
  </code></pre>
  
  <hr>
  
  <p><strong>Controller Action</strong> </p>
  
  <pre><code>public PartialViewResult SomeList()
  {
      int userid = ((CurrentUser )(User.Identity)).UserId; //Error shows here
  
      var list= listService.GetLists(userid);
      return PartialView("ListView", list);
  }
  </code></pre>
  
  <p><strong>Unit Test</strong></p>
  
  <pre><code>[Test]
  public void SomeList_Test()
  {
  
      var controllerContext = new Mock&lt;ControllerContext&gt;();
      var principal = new Moq.Mock&lt;IPrincipal&gt;();
  
      ListController controller = new ListController (listService);
  
      principal.SetupGet(x =&gt; x.Identity.Name).Returns("abc");
      controllerContext.SetupGet(x =&gt; x.HttpContext.User).Returns(principal.Object);
      controllerContext.SetupGet(p =&gt;      p.HttpContext.Request.IsAuthenticated).Returns(true);
      controller.ControllerContext = controllerContext.Object;
  
  }
  </code></pre>
  
  <p>Thanks in advance,
  Razack</p>