我正在尝试编写我的客户端控制器的索引方法的单元测试。
这是我的客户端控制器:
public ClientController(ApplicationUserManager clientManager, ApplicationRoleManager roleManager)
{
ClientManager = clientManager;
RoleManager = roleManager;
}
private ApplicationRoleManager _roleManager;
public ApplicationRoleManager RoleManager
{
get
{
return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
}
set
{
_roleManager = value;
}
}
private ApplicationUserManager _clientManager;
public ApplicationUserManager ClientManager
{
get
{
return _clientManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
set
{
_clientManager = value;
}
}
public async Task<ActionResult> Index(string filter, string error, string searchName, int? page, int? records)
{
List<string> filterCriteria = new List<string>();
filterCriteria.Add("Choose Email");
var listClients = new List<ApplicationUser>();
// Get the list of clients ( users with client role )
foreach (var user in ClientManager.Users.Where(u => u.IsActive == true && (u.FirstNames.Contains(searchName) || u.LastName.Contains(searchName)
|| searchName == null)).OrderBy(u => u.FirstNames).ToList())
{
if (await ClientManager.IsInRoleAsync(user.Id, "Client"))
{
listClients.Add(user);
filterCriteria.Add(user.Email);
}
}
ViewBag.emails = new SelectList(filterCriteria);
ViewBag.error = error;
if (filter == null || filter.Equals("Choose Email"))
{
return View(listClients.ToList().ToPagedList(page ?? 1, records ?? 15));
}
else
{
return View();
}
这是我尝试编写一个单元测试的尝试。
[TestMethod]
public void Index_Get_RetrievesAllClientFromRepository()
{
// Arrange,
ApplicationUser Client1 = GetClientNamed("1", 1, 1, DateTime.Now, "Abc", "Abc", "Xyz", "343433443", "abc@xyz.com", "M", "06091980-ABSD");
var userStore = new Mock<IUserStore<ApplicationUser>>();
var userManager = new UserManager<ApplicationUser>(userStore.Object);
userStore.Setup(x => x.CreateAsync(Client1))
.Returns(Task.FromResult(IdentityResult.Success));
userStore.Setup(x => x.FindByNameAsync(Client1.UserName))
.Returns(Task.FromResult(Client1));
var roleStore = new Mock<IRoleStore<IdentityRole>>();
var roleManager = new Mock<ApplicationRoleManager>(roleStore.Object);
var controller = new ClientController(
userStore.Object as ApplicationUserManager, roleManager.Object);
// Act
var resultTask = controller.Index("Choose Email", "", "", 1, 15);
resultTask.Wait();
var result = resultTask.Result;
var model = (List<ApplicationUser>)((ViewResult)result).Model;
CollectionAssert.Contains(model, Client1);
}
userStore.Object 总是为空。我在单元测试方面很新手,我寻找了很多解决方案,但没有这样的用例。任何帮助将不胜感激。
由于
as
强制转换,userStore.Object
显示为空,如果无法转换,则返回空。
userStore
定义为:
new Mock<IUserStore<ApplicationUser>>();
这意味着.Object
将是 IUserStore<ApplicationUser>
型 ,
这不是ApplicationUserManager
,所以你最终会得到null
.