I have an Asp.net core 6 Web api.
I make Integration tests with xUnit following the pattern here. WebApplicationFactory creates a client which the tests can use to make calls to the application instance.
Now, xUnit runs the class constructor for every test. To share a member between all tests in a test class, you need to use a xUnit class fixture. This is the example from MSDN:
public class IndexPageTests :
IClassFixture<CustomWebApplicationFactory<RazorPagesProject.Startup>>
{
private readonly HttpClient _client;
private readonly CustomWebApplicationFactory<RazorPagesProject.Startup>
_factory;
public IndexPageTests(
CustomWebApplicationFactory<RazorPagesProject.Startup> factory)
{
_factory = factory;
_client = factory.CreateClient(new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false
});
}
I don't understand - why they put the CreateClient method in the constructor? Obviously, it will create a new client for every test. Why don't we create a separate Fixture class, create the client there and just inject it in the Test class? For example:
public class TestFixture
{
public TestFixture()
{
var factory = new CustomWebApplicationFactory<RazorPagesProject.Startup>();
Client = factory.CreateClient(new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false
});
}
public HttpClient Client { get; }
}
public class TestClass : IClassFixture<TestFixture>
{
private readonly TestFixture _fixture;
public TestClass(TestFixture fixture)
{
_fixture = fixture;
}
[Fact]
public async Task FirstTest()
{
// use the fixture client directly
await _fixture.Client.GetAsync("..../url");
}
}
Does anyone see a problem with this approach? Memory leaks or other issues?
Is the fact that we instantiate CustomWebApplicationFactory<RazorPagesProject.Startup>() in the fixture constructor and not disposing it afterwards - causing memory problems, etc?