我得到一个错误,而嘲笑.net核心身份Rolemanager对象



我的问题如下我有一个方法叫GetListAsync()在Roleservice。此方法返回角色列表。为了方便示例,假设我有如下代码

var roles = await _roleManager.Roles.ToListAsync();返回角色;如何将Roles属性提交给mock。

如果你能帮忙我将非常高兴

public class RoleService : IRoleService
{
private readonly RoleManager<Role> _roleManager;
private readonly IMapper _mapper;
public RoleService(RoleManager<Role> roleManager, IMapper mapper = null)
{
_roleManager = roleManager;
_mapper = mapper;
}
public async Task<List<RoleDto>> GetListAsync()
{
var roles = await _roleManager.Roles.ToListAsync();
if (roles == null)
throw new NotFoundException(ResponseCode.Exception, ErrorMessageKey.ROLE_NOTFOUND);
return _mapper.Map<List<RoleDto>>(roles);
}
}

测试代码

public class RoleServiceTest
{
private Mock<RoleManager<Role>> _mockRoleManager;
private RoleManager<Role> _roleManager;
private RoleService _roleService;
private IMapper _mapper;
private readonly List<Role> _roles;
public RoleServiceTest()
{
var myProfile = new MappingProfile();
var configuration = new MapperConfiguration(cfg => cfg.AddProfile(myProfile));
_mapper = new Mapper(configuration);
_mockRoleManager = GetRoleManagerMock();
_roleManager = _mockRoleManager.Object;
_roleService = new RoleService(_roleManager, _mapper);
_roles = GetFakerRoles();
}

[Fact]
public async Task GetListAsync_ValidInput_RoleDto()
{
// mocking code 
var result = await _roleService.GetListAsync();
Assert.NotNull(result);
Assert.IsType<List<RoleDto>>(result);
}

private Mock<RoleManager<Role>> GetRoleManagerMock()
{

return new Mock<RoleManager<Role>>(
new Mock<IRoleStore<Role>>().Object,
new IRoleValidator<Role>[0],
new Mock<ILookupNormalizer>().Object,
new Mock<IdentityErrorDescriber>().Object,
new Mock<ILogger<RoleManager<Role>>>().Object);
}
private List<Role> GetFakerRoles()
{
return new Faker<Role>()
.RuleFor(r => r.Id, f => f.Random.Guid().ToString())
.RuleFor(r => r.Name, f => f.Random.Words())
.RuleFor(r => r.NormalizedName, (f, r) => r.Name.ToUpper())
.RuleFor(r => r.ConcurrencyStamp, f => f.Random.ToString())
.Generate(4);
}
}

// Create a mock object for the RoleManager class
var mockRoleManager = new Mock<RoleManager<IdentityRole>>();
// Setup the Roles property to return a list of roles
var roles = new List<IdentityRole> { new IdentityRole { Name = "Admin" }, new IdentityRole { Name = "User" } };
mockRoleManager.Setup(x => x.Roles).Returns(roles);
// Inject the mock object into your service or component that uses the RoleManager
var service = new MyService(mockRoleManager.Object);
// Now you can use the mock object to test your service or component
var result = await service.GetListAsync();
// Assert that the result is the expected list of roles
Assert.AreEqual(result, roles);

相关内容

  • 没有找到相关文章

最新更新