简体   繁体   中英

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");
        }
}

    

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM