我想單元測試一些依賴於UserManager
和RoleManager
的方法,並且遇到了一些困難。單元測試依賴於UserManager和RoleManager
我應該嘲笑UserManager
和RoleManager
,然後將它傳遞給AdminController
?或者我應該首先訪問AccountController
的默認SignIn
操作並進行身份驗證。我不確定如何做這兩種選擇或什麼是最好的方法來解決這個問題。
當不認證/實例我上UserManager
我的測試NullReferenceException異常
[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;
}
}
http://stackoverflow.com/questions/1452418/how-do-i-mock-the-httpcontext-in-asp-net-mvc-using-moq –
@PaulAbbott嘲笑HttpContext有什麼好處通過UserManager和RoleManager –
您將從代碼中的'HttpContext'獲得用戶管理器和角色管理器。如果你嘲笑'HttpContext'也返回一個模擬用戶和角色管理器,你根本不需要修改你的代碼。如果你直接模擬用戶和角色管理器,你需要改變你的代碼,以某種方式將它們注入到控制器中,而不是從'HttpContext'中獲取它們。 –