使用DbSet<>模拟实体框架6 .Include()

时间:2013-12-11 02:16:05

标签: linq entity-framework unit-testing

我想提供这个问题的背景资料。如果你愿意,可以跳过。很长一段时间以来,我一直密切关注stackoverflow和其他地方关于代码测试的正在进行的辩论,因为它与EF有关。一个阵营说,直接针对数据库进行测试,因为Linq to Objects& amp; Sql和实现。另一个人说通过嘲弄测试。

另一个意见分歧是使用存储库或接受DbContext和DbSet已经提供了工作单元和存储库模式的问题。在我使用EF的时候,我已经尝试过这些阵营提供的各种意见组合。无论我做了什么,EF证明很难测试。

我很高兴发现EF团队在EF 6中制作了DbSet more mockable。他们还提供了documentation如何模拟DbSet,包括使用Moq的异步方法。在处理涉及Web Api的最新项目时,我意识到如果我可以模拟EF,我可以跳过编写存储库,因为编写它们的正常原因是使事情可以测试。在阅读了this...

等一些博客文章之后,我们获得了灵感

- 背景结束---

实际问题是,遵循EF团队提供的关于如何使用Moq DbSet的示例代码,如果在任何代码中使用.Include(),则抛出ArgumentNullException。

其他related post on SO

这是我的DbContext界面:

public interface ITubingForcesDbContext
{
    DbSet<WellEntity> Wells { get; set; }

    int SaveChanges();

    Task<int> SaveChangesAsync();

    Task<int> SaveChangesAsync(CancellationToken cancellationToken);
}

这是我的控制器处理的主要实体

public class WellEntity
{
    public int Id { get; set; }
    public DateTime DateUpdated { get; set; }
    public String UpdatedBy { get; set; }

    [Required]
    public string Name { get; set; }
    public string Location { get; set; }

    public virtual Company Company { get; set; }

    public virtual ICollection<GeometryItem> GeometryItems
    {
        get { return _geometryItems ?? (_geometryItems = new Collection<GeometryItem>()); }
        protected set { _geometryItems = value; }
    }
    private ICollection<GeometryItem> _geometryItems;

    public virtual ICollection<SurveyPoint> SurveyPoints
    {
        get { return _surveyPoints ?? (_surveyPoints = new Collection<SurveyPoint>()); }
        protected set { _surveyPoints = value; }
    }
    private ICollection<SurveyPoint> _surveyPoints;

    public virtual ICollection<TemperaturePoint> TemperaturePoints
    {
        get { return _temperaturePoints ?? (_temperaturePoints = new Collection<TemperaturePoint>()); }
        protected set { _temperaturePoints = value; }
    }
    private ICollection<TemperaturePoint> _temperaturePoints;
}

这是直接使用EF DbContext

的控制器
 [Route("{id}")]
 public async Task<IHttpActionResult> Get(int id)
 {
        var query = await TheContext.Wells.
                                   Include(x => x.GeometryItems).
                                   Include(x => x.SurveyPoints).
                                   Include(x => x.TemperaturePoints).
                                   SingleOrDefaultAsync(x => x.Id == id);
        if (query == null)
        {
            return NotFound();
        }
        var model = ModelFactory.Create(query);
        return Ok(model);
}

最后这是失败的测试...

测试设置---

   [ClassInitialize]
   public static void ClassInitialize(TestContext testContest)
        {

            var well1 = new WellEntity { Name = "Well 1" };
            var well2 = new WellEntity { Name = "Well 2" };
            var well3 = new WellEntity { Name = "Well 3" };
            var well4 = new WellEntity { Name = "Well 4" };

            well1.GeometryItems.Add(new GeometryItem());
            well1.TemperaturePoints.Add(new TemperaturePoint());
            well1.SurveyPoints.Add(new SurveyPoint());

            well2.GeometryItems.Add(new GeometryItem());
            well2.TemperaturePoints.Add(new TemperaturePoint());
            well2.SurveyPoints.Add(new SurveyPoint());

            well3.GeometryItems.Add(new GeometryItem());
            well3.TemperaturePoints.Add(new TemperaturePoint());
            well3.SurveyPoints.Add(new SurveyPoint());

            well4.GeometryItems.Add(new GeometryItem());
            well4.TemperaturePoints.Add(new TemperaturePoint());
            well4.SurveyPoints.Add(new SurveyPoint());

            var wells = new List<WellEntity> { well1, well2, well3, well4 }.AsQueryable();

            var mockWells = CreateMockSet(wells);

            _mockContext = new Mock<ITubingForcesDbContext>();
            _mockContext.Setup(c => c.Wells).Returns(mockWells.Object);
   }

   private static Mock<DbSet<T>> CreateMockSet<T>(IQueryable<T> data) where T : class
    {
        var mockSet = new Mock<DbSet<T>>();

        mockSet.As<IDbAsyncEnumerable<T>>()
            .Setup(m => m.GetAsyncEnumerator())
            .Returns(new TestDbAsyncEnumerator<T>(data.GetEnumerator()));

        mockSet.As<IQueryable<T>>()
               .Setup(m => m.Provider)
               .Returns(new TestDbAsyncQueryProvider<T>(data.Provider));

        mockSet.As<IQueryable<T>>().Setup(m => m.Expression).Returns(data.Expression);
        mockSet.As<IQueryable<T>>().Setup(m =>m.ElementType).Returns(data.ElementType);
        mockSet.As<IQueryable<T>>().Setup(m=>m.GetEnumerator()).
        Returns(data.GetEnumerator());

        return mockSet;
   }

  [TestMethod]  
   public async Task Get_ById_ReturnsWellWithAllChildData()
    {
        // Arrange
        var controller = new WellsController(_mockContext.Object);

        // Act
        var actionResult = await controller.Get(1);

        // Assert
        var response = actionResult as OkNegotiatedContentResult<WellModel>;
        Assert.IsNotNull(response);
        Assert.IsNotNull(response.Content.GeometryItems);
        Assert.IsNotNull(response.Content.SurveyPoints);
        Assert.IsNotNull(response.Content.TemperaturePoints);
   }

TestDbAsyncQueryProvider&amp; TestDbAsyncEnumerator直接来自引用的EF团队文档。我已经尝试了几种不同的变体,我是如何为模拟创建数据的,但它没有任何运气。

5 个答案:

答案 0 :(得分:38)

如果对于如何通过 NSubstitute和Entity Framework 6 + 解决.Include("Foo")问题感兴趣而遇到此问题的任何人,我都可以绕过Include次来电通过以下方式:

var data = new List<Foo>()
{
    /* Stub data */
}.AsQueryable();

var mockSet = Substitute.For<DbSet<Foo>, IQueryable<Foo>>();
((IQueryable<Post>)mockSet).Provider.Returns(data.Provider);
((IQueryable<Post>)mockSet).Expression.Returns(data.Expression);
((IQueryable<Post>)mockSet).ElementType.Returns(data.ElementType);
((IQueryable<Post>)mockSet).GetEnumerator().Returns(data.GetEnumerator());

// The following line bypasses the Include call.
mockSet.Include(Arg.Any<string>()).Returns(mockSet);

答案 1 :(得分:31)

这是使用Moq的完整示例。您可以将整个示例粘贴到单元测试类中。感谢@ jbaum012和@Skuli的评论。我还建议the excellent tutorial from Microsoft

// An Address entity
public class Address
{
    public int Id { get; set; }
    public string Line1 { get; set; }
}

// A Person referencing Address
public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual Address Address { get; set; }
}

// A DbContext with persons and devices
// Note use of virtual (see the tutorial reference)
public class PersonContext : DbContext
{
    public virtual DbSet<Person> Persons { get; set; }
    public virtual DbSet<Address> Addresses { get; set; }
}

// A simple class to test
// The dbcontext is injected into the controller
public class PersonsController
{
    private readonly PersonContext _personContext;

    public PersonsController(PersonContext personContext)
    {
        _personContext = personContext;
    }

    public IEnumerable<Person> GetPersons()
    {
        return _personContext.Persons.Include("Address").ToList();
    }
}

// Test the controller above
[TestMethod]
public void GetPersonsTest()
{
    var address = new Address { Id = 1, Line1 = "123 Main St." };
    var expectedPersons = new List<Person>
    {
        new Person { Id = 1, Address = address, Name = "John" },
        new Person { Id = 2, Address = address, Name = "John Jr." },
    };

    var mockPersonSet = GetMockDbSet(expectedPersons.AsQueryable());
    mockPersonSet.Setup(m => m.Include("Address")).Returns(mockPersonSet.Object);

    var mockPersonContext = new Mock<PersonContext>();
    mockPersonContext.Setup(o => o.Persons).Returns(mockPersonSet.Object);

    // test the controller GetPersons() method, which leverages Include()
    var controller = new PersonsController(mockPersonContext.Object);
    var actualPersons = controller.GetPersons();
    CollectionAssert.AreEqual(expectedPersons, actualPersons.ToList());
}

// a helper to make dbset queryable
private Mock<DbSet<T>> GetMockDbSet<T>(IQueryable<T> entities) where T : class
{
    var mockSet = new Mock<DbSet<T>>();
    mockSet.As<IQueryable<T>>().Setup(m => m.Provider).Returns(entities.Provider);
    mockSet.As<IQueryable<T>>().Setup(m => m.Expression).Returns(entities.Expression);
    mockSet.As<IQueryable<T>>().Setup(m => m.ElementType).Returns(entities.ElementType);
    mockSet.As<IQueryable<T>>().Setup(m => m.GetEnumerator()).Returns(entities.GetEnumerator());
    return mockSet;
}

答案 2 :(得分:8)

使用此处并在此处引用答案Setup result for call to extension method,看起来Moq无法模拟静态扩展方法

我试图添加:

mockSet.Setup(t => t.FirstAsync()).Returns(Task.FromResult(data.First()));
mockSet.Setup(t => t.FirstAsync(It.IsAny<Expression<Func<T, bool>>>())).Returns(Task.FromResult(data.First()));

Moq抱怨说:

  

System.NotSupportedException:Expression引用一个方法   不属于模拟对象:t =&gt; t.FirstAsync()

所以似乎有三种选择:

  1. 重构您的代码以进一步隔离dbcontext,因此您不必这样做 测试这种行为
  2. 从DbSet切换到IDbSet而不是模拟 DbContext
  3. 允许您的测试创建一个SQL压缩数据库和 用数据填充它以运行测试

答案 3 :(得分:0)

EF团队提供的示例DbSet只是一个例子。

如果你想模仿Include (or FindAsync),你必须自己动手。

答案 4 :(得分:0)

我设法用通用方法模拟了Moq中的Include。尽管这并不涵盖Include()的所有用法,仅包括字符串和Expression,但它满足了我的需求:

public Mock<DbSet<T>> SetupMockSetFor<T>(Expression<Func<DbContext, DbSet<T>>> selector) where T : class
    {
        var mock = new Mock<DbSet<T>>();

        mock.ResetCalls();

        this.EntitiesMock.Setup(m => m.Set<T>()).Returns(mock.Object);
        this.EntitiesMock.Setup(selector).Returns(mock.Object);

        mock.Setup(x => x.Include(It.IsAny<string>())).Returns(mock.Object);

        try
        {
            mock.Setup(x => x.Include(It.IsAny<Expression<Func<T, object>>>()))
                .Returns(mock.Object);
        }
        catch
        {
            // Include only applies to some objects, ignore where it doesn't work
        }

        return mock;
    }

测试用法:

        var mockCourseSet = SetupMockSetFor(entities => entities.Courses);

使用中的方法:

var foundCourses = dbContext.Courses.Include(c => c.CourseParticipants).Where(c => c.Id = courseId)