Reputation: 13895
Each one of my XUnit test projects has an appsettings.json file that specifies a few settings. I have always used dependency injection with IConfiguration to retrieve these settings in my Test Fixture class. Now that I think about it I have absolutely no idea how the IConfiguration was resolved in the past since there is no Startup.cs and ConfigureServices methods in an XUnit project. But I swear it worked.
The following used to work and now it does not:
Fixture:
public class TestFixture : IDisposable
{
public IConfiguration Configuration { get; set; }
public TestFixture(IConfiguration configuration)
{
Configuration = configuration;
}
}
Test Class:
public class TestCases : IClassFixture<TestFixture>
{
public TestCases(TestFixture fixture)
{
}
}
The error I am receiving is the following:
Message: System.AggregateException : One or more errors occurred. ---- Class fixture type 'MyProj.Tests.TestFixture' had one or more unresolved constructor arguments: IConfiguration configuration ---- The following constructor parameters did not have matching fixture data: TestFixture fixture
Upvotes: 10
Views: 8709
Reputation: 595
I know this issue is very old but maybe the solution can be useful for someones.
I met with the same issue and fixed it by using WebApplicationFactory generic class. Hopefully, it will be the solution for the others.
replace
: IClassFixture<TestFixture> ->
: IClassFixture<WebApplicationFactory<Startup>>
for more detail, you can visit the official page
Upvotes: 3
Reputation: 1671
I wonder why I had code like you since documentation (https://xunit.github.io/docs/shared-context) doesn't say anything about using DI in Fixtures... In my case I solved it by removing the DI, because I had the same error you had.
Then I have such a code to have a services collection for unit tests.
var services = new ServiceCollection();
ConfigureServices(services);
IServiceProvider serviceProvider = services.BuildServiceProvider();
// Assign shortcuts accessors to registered components
UserManager = serviceProvider.GetRequiredService<UserManager<User>>();
RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole<string>>>();
My ConfigureServices() calls this code before registering services to collection, so this answers your question about IConfiguration. Note that I use .net core 2.1 now, had 2.0 before. But I'm still wondering like you and other people who commented, why did the DI not crash before?
private static IConfiguration LoadConfiguration()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
return builder.Build();
}
Upvotes: 0