Blake Rivell
Blake Rivell

Reputation: 13895

Unresolved constructor arguments error when trying to use dependency injection with XUnit

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

Answers (2)

malik masis
malik masis

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

barbara.post
barbara.post

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

Related Questions