代码之家  ›  专栏  ›  技术社区  ›  coolhand

使用Moq将用户添加到角色

  •  0
  • coolhand  · 技术社区  · 7 年前

    我模仿了一个 RoleManager IdentityRoles

    var roleList = new List<IdentityRole>()
    {
        new IdentityRole { Name = "R1" },
        new IdentityRole { Name = "R2" },
    };
    mockRoleManager.Setup(m => m.Roles).Returns(roleList.AsQueryable<IdentityRole>);
    

    我想在单元测试中将用户添加到此角色。当我使用

    await userManager.Object.AddToRoleAsync(user, "R1");
    

    它显示在调试期间从未将用户添加到角色。如何在单元测试期间填充角色?我用的是熏硝和莫克。

    AddToRoleAsync 方法,但没有运气。下面是我试图实现它的方式:

    //this will cause an error on the AddToRoleAsync method in the Act portion of the test
    userManager.Setup(u => u.AddToRoleAsync(It.IsAny<AppUser>(), It.IsAny<string>())).Returns(It.IsAny<Task<IdentityResult>>());
    

    也尝试过:

    var identityResult = new Mock<Task<IdentityResult>>();
    //this line gives an error 'Invalid setup on non-virtual (overridable in VB) member
    identityResult.Setup(r => r.Result.Succeeded).Returns(true);
    userManager.Setup(u => u.AddToRoleAsync(It.IsAny<AppUser>(), It.IsAny<string>())).Returns(identityResult.Object);
    
    0 回复  |  直到 7 年前