Search code examples
c#unit-testingasp.net-core.net-coremoq

How to mock service injected by HttpContext.RequestServices.GetService<> in derived controller?


I have base Api Controller defined like this

[ApiController]
public abstract class BaseController : ControllerBase
{
    private IMediator _mediator;

    protected IMediator Mediator => _mediator ??= HttpContext.RequestServices.GetService<IMediator>();
}

Auth controller derived from BaseController

public class AuthController : BaseController
{
    [HttpPost(ApiRoutes.Auth.Register)]
    public async Task<IActionResult> Register(UserRegistrationRequest request)
    {
        var response = await Mediator.Send(new UserRegistrationCommand(request.Email, request.Password));

        return Ok(response);
    }
}

How should mock IMediator service in unit tests? When services were injected using constructor DI I've just passed mocked services to constructor in tests, but in this scenario I'm not sure what to mock, probably HttpContext?


Solution

  • You should mock it using a library such as Moq or NSubstitute. Then wire up the methods using these libraries.