mercredi 14 avril 2021

How to mock HttpContext in ASP.NET Core

I'm trying to mock HttpContext to test my UsersController. The UsersController inherit from

public abstract class ControllerBase

and HttpContext is a property of ControllerBase

public HttpContext HttpContext { get; }

and here is the method in the UsersContoller, which I want to test

 public async Task<IActionResult> Register([FromBody] UserViewModel model)
        {
            _logger.LogDebug("Register new user");

            var user = mapper.Map<User>(model);
            user.Company.Active = false;

            var result = await userManager.CreateAsync(user, model.Password);

            if (result.Succeeded)
            {
                await userManager.AddToRoleAsync(user, Roles.NO_ACCESS);

                //send confirmation email

                string confirmationToken = userManager.GenerateEmailConfirmationTokenAsync(user).Result;

                HostString hostString = HttpContext.Request.Host; //I need to mock httpcontext for this 

                this.mailSender.SendConfirmationMailAsync(user, hostString, confirmationToken);

                return Ok();
            }
            else
            {
                _logger.LogInformation("User could not be registered Errors:");
                result.Errors.ToList().ForEach(e => _logger.LogInformation(e.Description));

                return BadRequest(result.Errors);
            }

        }

this is my BaseTestContoller, in which setup for tests is initialized

[SetUp]
        public void Setup()
        {
            var dbContext = CreateDbContext();

            CreateUserManager();
            CreateMailSender(dbContext);
            CreateMockImapper();
            CreateMockIlogger();
            
            usersController = new Mock<UsersController>(
               userManagerMock.Object,
               new CompanyService(dbContext),
               mailSenderMock,
               new Mock<IConfiguration>().Object,
               iMapperMock.Object,
               iLoggerFactoryMock.Object);

        }

i've tried many options, but it wasn't successful therefor it would be nice if someone could help me. Thanks in advance

Aucun commentaire:

Enregistrer un commentaire