Breaking

Monday, April 19, 2021

XUnit–Dependency Injection

To use the standard IoC container inside your Xunit tests, I would recommend to use a separate fixture. Inside this fixture you can add all dependencies to the ServiceCollection and build the ServiceProvider:

public class ContainerFixture
{
public ContainerFixture()
{
var serviceCollection = new ServiceCollection();
serviceCollection
.AddHttpContextAccessor()
.AddHttpClient();
ServiceProvider = serviceCollection.BuildServiceProvider();
}
public ServiceProvider ServiceProvider { get; private set; }
}

Now you can use the IoC container inside your tests by injecting the fixture inside the constructor:

public class MyContainerEnabledTests:IClassFixture<ContainerFixture>
{
private ServiceProvider _serviceProvider;
public MyContainerEnabledTests(ContainerFixture fixture)
{
_serviceProvider = fixture.ServiceProvider;
}
[Fact]
public void Test1()
{
var dependency=_serviceProvider.GetService<MyDependency>();
}
}

No comments:

Post a Comment