如何模拟Asp.net身份UserManager列出特定角色

时间:2016-01-27 16:12:02

标签: asp.net-mvc unit-testing asp.net-identity moq

我正在尝试编写ClientController的索引方法的单元测试。

这是我的ClientController:

   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始终为null。我是单位测试的新手,我找了很多解决方案,但没有这样的用例。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

由于as强制转换,

userStore.Object将变为空,如果转换不可能,则返回null。

userStore定义为:

new Mock<IUserStore<ApplicationUser>>();

表示.Object的类型为IUserStore<ApplicationUser>

不是ApplicationUserManager,因此您最终得到null