代码之家  ›  专栏  ›  技术社区  ›  Kamran Khan

使用单元测试ASP。NET核心

  •  0
  • Kamran Khan  · 技术社区  · 10 月前

    我正在开发一个应用程序,在这个应用程序中,我需要模拟一个用户管理器,但从中得到一个空响应 CreateAsync 。以下是我的服务和单元测试代码。

    [Fact]
    public async Task RegisterUser_Exceptions()
    {
        // Initialize AutoMapper with the defined profile
        var configuration = new MapperConfiguration(cfg => cfg.AddProfile<UserMapperProfile>());
        var mapper = configuration.CreateMapper();
    
        // Mock the UserManager
        var userStoreMock = new Mock<IUserStore<AppUser>>();
        var userManagerMock = new Mock<UserManager<AppUser>>(
                userStoreMock.Object,
                new Mock<IOptions<IdentityOptions>>().Object,
                new Mock<IPasswordHasher<AppUser>>().Object,
                new IUserValidator<AppUser>[0],
                new IPasswordValidator<AppUser>[0],
                new Mock<ILookupNormalizer>().Object,
                new Mock<IdentityErrorDescriber>().Object,
                new Mock<IServiceProvider>().Object,
                new Mock<ILogger<UserManager<AppUser>>>().Object);
    
        // Setup CreateAsync to return a successful IdentityResult
        userManagerMock.Setup(x => x.CreateAsync(It.IsAny<AppUser>(), It.IsAny<string>()))
                .ReturnsAsync(IdentityResult.Success);
    
        // Instantiate the UserManagementService with the actual AutoMapper instance
        var userManagementService = new UserManagementService(userManagerMock.Object, mapper);
    
        // Create a UserRegisterationDto with all required properties
        var userRegistrationDto = new UserRegisterationDto
            {
                email = "[email protected]",
                msisdn = "24242455",
                externalUserId = "external-id"
            };
    
        // Call the RegisterUserAsync method
        var result = await userManagementService.RegisterUserAsync(userRegistrationDto);
    
        // Assert that the result is not null
        Assert.NotNull(result);
    
        // Assert that the result is success
        Assert.True(result.Succeeded);
    
        // Verify that CreateAsync was called with the expected AppUser
        userManagerMock.Verify(x => x.CreateAsync(It.IsAny<AppUser>(), userRegistrationDto.email), Times.Once);
    }
    

    服务器管理器:

    public class UserManagementService : IUserManagementService
    {
         private readonly UserManager<AppUser> _userManager;
         private readonly IMapper _mapper;
    
         public UserManagementService(UserManager<AppUser> userManager, IMapper mapper)
         {
             _userManager = userManager;
             _mapper = mapper;
         }
    
         public async Task<IdentityResult> RegisterUserAsync(UserRegisterationDto userRequest)
         {
             var appUser = _mapper.Map<UserRegisterationDto, AppUser>(userRequest);
             var result = await _userManager.CreateAsync(appUser);
             return result;
         }
    }
    

    结果来自 CreateAsync 总是 null .

    1 回复  |  直到 10 月前
        1
  •  1
  •   Michał Turczyn    10 月前

    UserManager 有两个过载 CreateAsync ,你在嘲笑错误的方法。

    你需要使用

    userManagerMock.Setup(x => x.CreateAsync(It.IsAny<AppUser>()))
        .ReturnsAsync(IdentityResult.Success);
    

    此外,你对 result 没有意义,因为结果就是你在模拟中所定义的。所以你只是验证了你是否以特定的方式定义了mock,这不是UT的主题。

    唯一正确的断言是检查是否 CreateAsync 使用正确的参数调用。