我正在尝试对 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;
}
}
}