Illep
Illep

Reputation: 16851

XUnit with Dependency Injection constructor parameters did not have matching fixture data

I am getting the following error when I am trying to execute a simple Unit Test using XUnit.

The following constructor parameters did not have matching fixture data: IMyRepository myRepo

Scenario: When I supplied with the name of a student, I am checking if the student school is correct.] Code

public class UnitTest1
{
        private readonly IMyRepository _myRepo;


        public UnitTest1(IMyRepository myRepo)
        {
            this._myRepo = myRepo;
        }

        [Fact]
        public void TestOne()
        {
            var name = "Hillary";

            var r = this._myRepo.FindName(name);
            Assert.True(r.School == "Capital Hill School");
        }
}

    

Upvotes: 0

Views: 1892

Answers (1)

Christopher Hamkins
Christopher Hamkins

Reputation: 1649

To inject a dependency in an XUnit test you need to define a fixture. The object to be provided must have a paramaterless constructor, and the test class has to be derived from IClassFixture<YourFixture>.

So something like this should work:

public class MyRepository : IMyRepository
{
    public MyRepository() // No parameters
    {
        // ... Initialize your repository
    }
    // ... whatever else the class needs 
}

public class UnitTest1 : IClassFixture<MyRepository>
{
        private readonly IMyRepository _myRepo;

        public UnitTest1(MyRepository myRepo)
        {
            this._myRepo = myRepo;
        }

        [Fact]
        public void TestOne()
        {
            var name = "Hillary";

            var r = this._myRepo.FindName(name);
            Assert.True(r.School == "Capital Hill School");
        }
}

You can also define a test Collection and its fixture in the CollectionDefinition

The documentation at https://xunit.net/docs/shared-context explains how to do it.

Upvotes: 0

Related Questions