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;
}
前もってありがとう、ラザック