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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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