我的问题是这样的,我在Roleservice中有一个名为GetListAsync()的方法,这个方法返回一个角色列表,为了举例,假设我有这样一段代码
变量角色= await _roleManager.Roles.ToListAsync();返回角色;
如何提交Roles属性以进行模拟。
如果你能帮忙我会很高兴
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);
}
}
1条答案
按热度按时间mzmfm0qo1#