如何对create方法进行单元测试



我想在方法下面写一个单元测试。

使用这个方法,我可以添加一个用户,这是很好的工作。用户可以保存


public async Task<UserModel> SaveAsync(UserModel model)
{
if (string.IsNullOrEmpty(model.ExternalUserId))
{
var extUser = await identityManagementService.CreateUser(model);
user = new ApplicationUser()
{
ExternalUserId = extUser.UserId,
IsActive = true,
UserName = model.Email,
};
user.Id = Guid.NewGuid();
var exists = false;

await applicationUserRepository.AddOrUpdateAsync(user, a => exists);
}
await applicationUserRepository.SaveAsync();
var IsSaved = await identityManagementService.GetUserById(user.ExternalUserId); // to check the user is saved

return model;
}

单元测试


[Fact]
public async Task SaveAsync_Should_AddORUpdate_WhenExternalUserIdDoesNOtExsitsAndProfileImgIsNull() // userRole is exist
{
var userModel = UserMockData.UserCorrectModelWithExternalUsserIdEmpty();
var applicationRole = UserMockData.ApplicationRole();
_identityManagementService.Setup(x => x.CreateUser(userModel)).Returns(Task.FromResult(UserMockData.User()));
// _identityManagementService.Setup(x => x.GetUserById(userModel.ExternalUserId)).Returns(() => null);
_applicationRoleRepository.Setup(x => x.FindAsync(userModel.RoleId)).Returns(Task.FromResult(applicationRole));
_identityManagementService.Setup(x => x.AssignUserRoles(It.Is<String>(g => g != String.Empty), applicationRole.ExternalRoleId)).Returns(Task.FromResult(true));
var sut = new UserManagementService(
_applicationRoleRepository.Object,
_applicationUserRepository.Object,
_applicationRolePermissionRepository.Object,
_identityManagementService.Object,
_smtpEmailService.Object,
_logger.Object
);
// Act
var result = await sut.SaveAsync(userModel);
//Asset
result.Should().NotBeNull();
var x = _identityManagementService.Object.GetUserById(userModel.ExternalUserId).Result; // this is null
var y = _applicationRoleRepository.Object.ListAsync(false).Result?.Count(); //  this is also null
x.Should().Be(1);

}

当我在调试模式下检查方法时var IsSaved = await identityManagementService.GetUserById(user.ExternalUserId); // to check the user is saved这行不为空

但是当我检查单元测试调试模式时,var IsSaved = await identityManagementService.GetUserById(user.ExternalUserId); // to check the user is saved为null

如何验证/测试用户是否被此方法保存?

请指引我。

因为您没有模拟GetUserById方法。您必须模拟GetUserById方法。在mock中,我们没有做实际的创建,这就是为什么你的GetUserById给出的结果为null。

请在您的测试方法中添加以下代码-

_identityManagementService.Setup(x => x.GetUserById(userModel.ExternalUserId)).Returns(true);

相关内容

  • 没有找到相关文章

最新更新