Randy
Randy

Reputation: 1287

How do I inject dependencies in a Moq for a Unit Test

I have a DbContext that I am unit testing with Moq. The DbContext has two dependencies that I Inject with Autofac in my main program. When I unit test Moq tells me it cannot find a parameterless constructor. I add a parameterless constructor in my DbContext and the unit tests pass. Is there not a way to inject the DbContext dependencies with Autofac like I do in my main program?

Here is my unit test:

    [TestMethod]
    public void GetAllPersons_orders_by_name()
    {
        var data = new List<Person>
        {
            new Person { FirstName = "John", LastName = "Doe"},
            new Person { FirstName = "Bill" , LastName = "Smith"},
            new Person { FirstName = "Fred" , LastName = "Williams"}
        }.AsQueryable();

        var mockSet = new Mock<DbSet<Person>>();
        mockSet.As<IQueryable<Person>>().Setup(m => m.Provider).Returns(data.Provider);
        mockSet.As<IQueryable<Person>>().Setup(m => m.Expression).Returns(data.Expression);
        mockSet.As<IQueryable<Person>>().Setup(m => m.ElementType).Returns(data.ElementType);
        mockSet.As<IQueryable<Person>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator());

        var mockContext = new Mock<MyContext>();

        mockContext.Setup(c => c.People).Returns(mockSet.Object);

        var service = new PeopleService(mockContext.Object);
        var people = service.GetAllPeople();

        Assert.AreEqual(3, people.Count);
        Assert.AreEqual("John", people[0].FirstName);
        Assert.AreEqual("Bill", people[1].FirstName);
        Assert.AreEqual("Fred", people[2].FirstName);
    }

Upvotes: 0

Views: 2068

Answers (1)

phil322
phil322

Reputation: 81

You can add your constructor args when you create the mock object. So in this case it would be like:

var mockContext = new Mock<MyContext>(myDependecy1, myDependency2 ...);

Upvotes: 2

Related Questions