使用Moq将用户添加到角色

时间:2018-06-17 02:16:09

标签: c# unit-testing moq xunit

我嘲笑了RoleManagerIdentityRoles

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");

它表明在调试期间从未将用户添加到角色。如何在单元测试期间填充角色?我正在使用xUnit和Moq。

正如评论中所建议的那样,我尝试设置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 个答案:

没有答案