Search code examples
asp.net-coreintegration-testing

ASP.NET Core access to HttpContext in integration tests


I am using Microsoft.AspNetCore.Testing.WebApplicationFactory<Startup> in my integration tests. I'm trying to access _fixture.Server.Host property, but it's throwing an exception
"The TestServer constructor was not called with a IWebHostBuilder so IWebHost is not available".

Could anyone tell, why is it so?
Here is my code:

public class OneTest:IClassFixture<WebApplicationFactory<Startup>>{
    private readonly WebApplicationFactory<Startup> _fixture;
    public OneTest(WebApplicationFactory<Startup> fixture){
        _fixture=fixture;
    }
    [Fact]
    public async Task TestCanBeAuthenticated(){
        var host=_fixture.Server.Host; // Exception is being thrown
        // ... code ...
    }
    
}

Solution

  • My initial goal was to get access to HttpContext, so turned out that TestServer.SendAsync(...) returns Task<HttpContext> with all necessary properties like Response, User etc.