Search code examples
c#.netunit-testingmoqxunit

unit test How to do a unit test for create method


I want to write a unit test below method.

Using this method I can add a user and this is works fine. user can be saved.


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;

}

unit test


 [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);


        }

When I check the method in debugging mode var IsSaved = await identityManagementService.GetUserById(user.ExternalUserId); // to check the user is saved this line is not null.

But when I checked unit test debug mode, var IsSaved = await identityManagementService.GetUserById(user.ExternalUserId); // to check the user is saved is null

How can I verify/test the user is saved by this method?

Please guide me.


Solution

  • Because you have not mock the GetUserById method. You have to mock the GetUserById method. In mock we are not doing actual creation that's why your GetUserById is giving result as null.

    Please add below code in your test method -

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