C# 使用Moq将用户添加到角色

C# 使用Moq将用户添加到角色,c#,unit-testing,moq,xunit,C#,Unit Testing,Moq,Xunit,我已经模拟了一个角色管理器和IdentityRoles: var roleList = new List<IdentityRole>() { new IdentityRole { Name = "R1" }, new IdentityRole { Name = "R2" }, }; mockRoleManager.Setup(m => m.Roles).Returns(roleList.AsQueryable<IdentityRole>); 这表明

我已经模拟了一个
角色管理器
IdentityRoles

var roleList = new List<IdentityRole>()
{
    new IdentityRole { Name = "R1" },
    new IdentityRole { Name = "R2" },
};
mockRoleManager.Setup(m => m.Roles).Returns(roleList.AsQueryable<IdentityRole>);
这表明用户在调试期间从未添加到角色中。如何在单元测试期间填充角色?我正在使用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>>());
//这将导致测试的Act部分中的AddToRoleAsync方法出错
Setup(u=>u.AddToRoleAsync(It.IsAny(),It.IsAny())。返回(It.IsAny());
并尝试:

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);
var identityResult=new Mock();
//此行给出错误“非虚拟(在VB中可重写)成员上的设置无效”
identityResult.Setup(r=>r.Result.successed)。返回(true);
Setup(u=>u.AddToRoleAsync(It.IsAny(),It.IsAny())。返回(identityResult.Object);

您需要确保已模拟了将在AddToRoleAsync中调用的RoleManager方法。@FeiyuZhou我尝试了模拟UserManager方法,但没有成功。请参阅问题中的我的编辑您需要使用ReturnsAsync,因为方法为returnTask@FeiyuZhou当我尝试
userManager.Setup(u=>u.AddToRoleAsync(It.IsAny(),It.IsAny()).ReturnsAsync(identityResult.Object)错误为“无法从任务转换到系统.Func(已解释)该值不能是
identityResult.Object
,它应该是真实的对象。或者,您需要模拟程序中调用的IdentityRole的方法和属性。
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);