J
J
Jarwis2014-11-06 12:17:00
Unit testing
Jarwis, 2014-11-06 12:17:00

Moq and Autofac. Why are there problems when simulating a DbContext?

I recently switched from Castle.Windsor to Autofac and had a problem with unit tests, namely when creating a mock DbContext.
Everything works fine here:

var set = new Mock<IDbSet<Company>>();
            set.Setup(c => c.GetEnumerator()).Returns(data.GetEnumerator());
            set.Setup(c => c.ElementType).Returns(data.ElementType);
            set.Setup(c => c.Expression).Returns(data.Expression);
            set.Setup(c => c.Provider).Returns(data.Provider);

            var context = new Mock<MyDbContext>();
            context.Setup(c => c.Companies).Returns(set.Object);

But as soon as I add a simulated Remove method, a NullReferenceException is thrown in the code, which is sort of like MyDbContext.Companies is null.
context.Setup(c => c.Companies.Remove(It.IsAny<Company>()))
                .Returns<Company>(c => _data.Remove(c) ? c : null);

I'm adding this right below the first listing.
What is it? Where to dig and how to solve? Am I using Moq incorrectly or something else? Because there were no such problems with Castle.Windsor.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question