Click here to Skip to main content
15,891,253 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi,

I am trying to set a fake httpcontext for an api call for a integration test but httpContext is always null when debugging through controller.

Controller method:
[HttpGet]
[Route("GetUsername")]
public IActionResult GetUsername() =>
    new UserDataHandler(_userRepository).GetUsername(HttpContext.User.GetNameIdentifier());


I have a base IntegrationTest class which all integration tests inherit from. This class basically calls custom WebApplicationFactory which creates services used in testing eg.

protected IntegrationTest(bool seedUsers)
{
    var appFactory = new CoreWebApplicationFactory<TStartup>(seedUsers);
    Client = appFactory.CreateClient(new WebApplicationFactoryClientOptions
    {
        AllowAutoRedirect = false
    });

    LocalStorageService = appFactory.Services.GetRequiredService<ILocalStorageService>();
    AuthenticationStateProvider = new ApiAuthenticationStateProvider(Client, LocalStorageService);
}


What I have tried:

I am unsure how HttpContext fits into this. Is there a similar build in implementation to create HttpContext similar to how Http 'Client' is being created above? Or does it need to be implemented directly in the testing method somehow?

I was thinking of adding
IHttpContextAccessor httpContextAccessor
as a service but that would mean I would need to pass it in into controllers, and I don't really see the point of doing it since HttpContext is already available in the Controller, the api work fine when testing manually through the website but I am struggling to get it working through integration tests.

Any help would be appricated
Posted
Comments
James Walsh Jr 31-Dec-20 13:44pm    
Are you using a framework to mock the factory output?
Member 13081540 1-Jan-21 14:00pm    
No, I am creating a fake startup services for integration tests

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900