gpt4 book ai didi

c# - IdentityRole 上缺少类型映射配置或不受支持的映射

转载 作者:行者123 更新时间:2023-12-02 14:05:28 24 4
gpt4 key购买 nike

我正在写unit tests还有这个mapper再次让我悲伤。我从上一篇文章中了解到我不能 Mock mapper ,我必须立即使用它。所以我创建了maps但它说缺少类型 map configuration .

    public RoleDto GetSingle([FromRoute] string id)
{
var r = roleManagerWrapper.GetSingleRole(id);
return mapper.Map<RoleDto>(r);
}

当它尝试 map 时它就中断了物体。有什么特别的mapping对于 Task <IdentityRole>需要实现吗?

    public async Task<IdentityRole> GetSingleRole(string roleId)
{
var role = await this.roleManager.Roles.SingleOrDefaultAsync(r => r.Id == roleId);

return role;
}

这是我的测试,仅计算创建的角色数量。

    [Test]
public async Task Get_Single()
{
TestSetup();

var roleManagerWrapperMock = new Mock<IRoleManagerWrapper>();


var adminRole = new IdentityRole()
{
Name = "Admin",
Id = "4a8de423-5663-4831-ac07-7ce92465b008"
};

var managerRole = new IdentityRole()
{
Name = "Manager",
Id = "40f74162-3359-4253-9b5a-ad795b328267"
};
ApplicationDbContext.Roles.Add(managerRole);
ApplicationDbContext.Roles.Add(adminRole);

ApplicationDbContext.SaveChanges();

var sut = new RolesController(roleManagerWrapperMock.Object, ApplicationDbContext, Mapper);
var result = sut.GetSingle("4a8de423-5663-4831-ac07-7ce92465b008");
Assert.AreEqual(result.UserCount, 1);
}


protected void TestSetup(string databaseName = null)
{
if (databaseName == null)
{
databaseName = GetTestName();
}

TestCleanup();
ServiceProvider = new ServiceCollection()
.AddEntityFrameworkInMemoryDatabase()
.BuildServiceProvider();

dbContextOptions = new DbContextOptionsBuilder<ApplicationDbContext>()
.UseInMemoryDatabase(databaseName)
.UseInternalServiceProvider(ServiceProvider)
.Options;

ApplicationDbContext = new ApplicationDbContext(dbContextOptions);

var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<RoleDto, IdentityRole>();
cfg.CreateMap<IdentityRole, RoleDto>();
cfg.CreateMap<CreateRoleDto, IdentityRole>().ReverseMap();
cfg.CreateMap<UpdateRoleDto, IdentityRole>().ReverseMap();
});
Mapper = config.CreateMapper();
}

最佳答案

该操作需要重构以使用正确的异步语法,因为 GetSingleRole返回Task<IdentityRole>

public Task<RoleDto> GetSingle([FromRoute] string id) {
IdentityRole r = await roleManagerWrapper.GetSingleRole(id);
return mapper.Map<RoleDto>(r);
}

测试也相应更新

[Test]
public async Task Get_Single() {
//Arrange
TestSetup();

var roleManagerWrapperMock = new Mock<IRoleManagerWrapper>();

//...omitted for brevity

var sut = new RolesController(roleManagerWrapperMock.Object, ApplicationDbContext, Mapper);

//Act
RoleDto result = await sut.GetSingle("4a8de423-5663-4831-ac07-7ce92465b008");

//Assert
Assert.AreEqual(result.UserCount, 1);
}

关于c# - IdentityRole 上缺少类型映射配置或不受支持的映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59791536/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com