【发布时间】:2016-03-01 20:49:24
【问题描述】:
我正在尝试对依赖 UserManager 和 RoleManager 的一些方法进行单元测试,但遇到了一些困难。
我是否应该模拟UserManager 和RoleManager,然后将其传递给AdminController?还是我应该首先访问AccountController 的默认SignIn 操作并进行身份验证。我不确定如何做这两种选择或最好的方法是什么。
当不验证/实例化管理器时,我在 UserManager 上得到 NullReferenceExceptions
我的测试
[Test]
public void MaxRole_SuperAdmin()
{
var adminController = new AdminController();
var maxRole = adminController.GetMaxRole(SuperAdminUserId);
Assert.AreEqual(maxRole, "Super Admin");
}
控制器和方法
[Authorize(Roles = "APGame Admin, APGame Investigator")]
[RequireHttps]
public class AdminController : Controller
{
private ApplicationUserManager _userManager;
public ApplicationUserManager UserManager
{
get { return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>(); }
private set { _userManager = value; }
}
private ApplicationRoleManager roleManager;
public ApplicationRoleManager RoleManager
{
get
{
return roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
}
private set { roleManager = value; }
}
public string GetMaxRole(string userId)
{
IEnumerable<string> userRoles = UserManager.GetRoles(userId);
string role = null;
if (userRoles.Contains("APGame Admin"))
{
if (userRoles.Contains("TeVelde Group") && userRoles.Contains("Genomics Group"))
role = "Super Admin";
else role = "Admin";
}
else if (userRoles.Contains("APGame Investigator"))
{
role = "Investigator";
}
else if (userRoles.Contains("APGame User"))
{
role = "User";
}
else
{
//TODO: Log no role, HIGH
}
return role;
}
}
【问题讨论】:
-
@PaulAbbott 在 UserManager 和 RoleManager 上模拟 HttpContext 有什么好处
-
您从代码中的
HttpContext获取用户管理器和角色管理器。如果你模拟HttpContext来返回一个模拟的用户和角色管理器,你根本不需要修改你的代码。如果直接模拟用户和角色管理器,则需要更改代码以某种方式将它们注入控制器,而不是从HttpContext获取它们。
标签: c# asp.net-mvc unit-testing mocking asp.net-identity