代码之家  ›  专栏  ›  技术社区  ›  V0ldek

如何进行单元测试。包括用于实体框架的预加载

  •  -1
  • V0ldek  · 技术社区  · 7 年前

    我有一个方法,其目的是从 DbSet 相关数据已经被载入其中(它有一个序列 .Includes 在它的逻辑中)相关字段是 virtual IEnumerable 而且很懒。

    现在我想对这个方法进行单元测试,以检查它是否加载了我需要的所有数据。我不知道该如何处理它,我可以创建一个预期的实体并用数据填充它,但只需模拟 IDbSet (我用的是MOQ)不起作用-如果我把所有的 包括 从被测试的方法中,它仍然会返回所有相关的实体,这不是它在实际数据库中所具有的“活动”行为(实体不会被加载,方法的契约也不会实现)。

    那么,我该怎么嘲笑 IDBSET 所以它实际上是懒惰的加载,没有显式的 包括 ?或者我做的完全错误,还有其他方法来测试这个方法?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Steve Py    7 年前

    MyParentEntity entity = null;
    using (var dbContext = new MyDbContext(connectionString))
    {
        var myRepository = new MyRepository(dbContext);
        entity = myRepository.GetEntityById(1);
    } // leave the scope of the DbContext.
    
    // example asserts...
    Assert.IsNotNull(entity.Relative, "Relative was not eager loaded."); // Null or EF Exception if proxy attempts to lazy-load.
    Assert.IsTrue(entity.Children.Count == 3, "Children were not eager loaded.");