【发布时间】:2015-01-25 09:34:40
【问题描述】:
我正在尝试对 n 层应用程序、服务层、存储库层和 Web api 控制器执行单元测试。我的存储库正在检查 Thread.CurrentPrincipal 对象以获取当前用户。这是我遇到问题的地方,当我创建从 IPrincipal 继承的实现类时,它确实允许我设置 IsUserAuthenticated。有没有办法为我的单元测试模拟这个。我想将 Thread.CurrentPrincipal 设置为我的实现对象。我将如何以这种方式模拟用户?
在我的 RepositoryBase 代码中,我调用以下命令来确定用户是否已通过身份验证:
public bool IsUserAuthenticated
{
get { return ((UserPrincipal)Principal).Identity.IsAuthenticated; }
}
实际测试如下:
Contract.Requires<UserAccessException>(IsUserAuthenticated, "Illegal Access.");
我正在从下面的 UserPrincipal 中提取 IsUserAuthenticated:
namespace HeyLetsTrain.Toolkit.Helper.Authentication
{
public class UserPrincipal : IPrincipal
{
IIdentity _identity;
string[] _role;
string _emailAddress;
public UserPrincipal(string name, string[] role)
{
if (role != null)
{
_role = new string[role.Length];
_role.CopyTo(role, 0);
Array.Sort(_role);
}
_identity = new GenericIdentity(name);
}
public IIdentity Identity
{
get { return _identity; }
}
public string EmailAddress
{
get { return _emailAddress; }
set { this._emailAddress = value; }
}
public bool IsInRole(string role)
{
return Array.BinarySearch(_role, role) >= 0 ? true : false;
}
public bool IsInAllRoles( params string [] roles )
{
foreach (string searchrole in roles )
{
if (Array.BinarySearch(_role, searchrole) < 0 )
return false;
}
return true;
}
public bool IsInAnyRoles( params string [] roles )
{
foreach (string searchrole in roles )
{
if (Array.BinarySearch(_role, searchrole ) > 0 )
return true;
}
return false;
}
}
}
【问题讨论】:
-
在您提到的有关 Thread.CurrentPrincipal 的问题中,但在示例中您有 ((UserPrincipal)Principal)。这个 Principal 东西的起源是什么 - 它是你的 RepositoryBase 中的属性吗?
-
Principal 和 UserPrincipal 类型有哪些定义?
-
有一个 Principal 属性,它返回 Thread.CurrentPrincipal 和 UserPrincipal,它是 IPrincipal 的一个实现。
标签: c# unit-testing iprincipal