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
Several key steps are involved in utilizing dependency injection in an xUnit test project covered below. Defining a class to retain dependency injection provider’s instance We need to define a class to instantiate Microsoft’s dependency injection service provider to add services and configurations.
Ideally for me xUnit should use the default parameterless constructor if it's available instead of throwing an exception public class ConfigurationFixture { public string ConnectionString { get; } public ConfigurationFixture () { var timestamp = DateTimeOffset.
There are certainly cases when developers want to run integration tests against their code wired up heavily by dependency injection. xUnit is a mature, loved-by-developers, and robust test framework for testing .net code. A slight downside of xUnit is that it lacks an out-of-the-box solution to inject dependencies.
A slight downside of xUnit is that it lacks an out-of-the-box solution to inject dependencies. Fortunately, xUnit has been equipped with the “Fixture” feature, which is meant to share contexts among test classes or tests within the same test class.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With