0

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

    
1
  • Have you also defined a class or collection fixture to inject the IMyRepository ? See xunit.net/docs/shared-context for example. If so, please provide the code for the fixture. Commented Mar 10, 2022 at 13:55

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.