使用Mock IDbSet对Entity Framework进行unit testing

我以前从来没有真正完成过unit testing,而且在第一次测试时我遇到了绊倒和绊倒。 问题是_repository.Golfers.Count(); 始终表示DbSet为空。

我的测试很简单,我只想添加一个新的高尔夫球手

 [TestClass] public class GolferUnitTest //: GolferTestBase { public MockGolfEntities _repository; [TestMethod] public void ShouldAddNewGolferToRepository() { _repository = new MockGolfEntities(); _repository.Golfers = new InMemoryDbSet(CreateFakeGolfers()); int count = _repository.Golfers.Count(); _repository.Golfers.Add(_newGolfer); Assert.IsTrue(_repository.Golfers.Count() == count + 1); } private Golfer _newGolfer = new Golfer() { Index = 8, Guid = System.Guid.NewGuid(), FirstName = "Jonas", LastName = "Persson" }; public static IEnumerable CreateFakeGolfers() { yield return new Golfer() { Index = 1, FirstName = "Bill", LastName = "Clinton", Guid = System.Guid.NewGuid() }; yield return new Golfer() { Index = 2, FirstName = "Lee", LastName = "Westwood", Guid = System.Guid.NewGuid() }; yield return new Golfer() { Index = 3, FirstName = "Justin", LastName = "Rose", Guid = System.Guid.NewGuid() }; } 

我使用Entity Framework和代码优先构建了一个数据模型。 我已经为IDbSet嘲笑了一个派生类,以便测试我的上下文(对网上的人来说,我记不清楚了)

 public class InMemoryDbSet : IDbSet where T : class { readonly HashSet _set; readonly IQueryable _queryableSet; public InMemoryDbSet() : this(Enumerable.Empty()) { } public InMemoryDbSet(IEnumerable entities) { _set = new HashSet(); foreach (var entity in entities) { _set.Add(entity); } _queryableSet = _set.AsQueryable(); } public T Add(T entity) { _set.Add(entity); return entity; } public int Count(T entity) { return _set.Count(); } // bunch of other methods that I don't want to burden you with } 

当我调试并逐步执行代码时,我可以看到我实例化_repository并用三个伪造的高尔夫球手填充它,但是当我退出添加function时, _respoistory.Golfers再次为空。 当我添加一个新的高尔夫球手时,运行_set.Add(entity)并添加高尔夫球手,但是再次_respoistory.Golfers为空。 我在这里想念的是什么?

更新

我很抱歉是个白痴,但我没有在我的MockGolfEntities上下文中实现该set 。 我没有的原因是我之前尝试过但无法弄清楚如何,继续前进并忘记它。 那么,我该如何设置IDbSet ? 这是我尝试过的,但它给了我一个Stack Overflow错误。 我觉得自己像个白痴,但我无法弄清楚如何编写set函数。

 public class MockGolfEntities : DbContext, IContext { public MockGolfEntities() {} public IDbSet Golfers { get { return new InMemoryDbSet(); } set { this.Golfers = this.Set(); } } } 

您不需要实现get / set,以下代码应该足以为您生成上下文。

 public class MockGolfEntities : DbContext, IContext { public MockGolfEntities() {} public IDbSet Golfers { get; set;} } 

我已经实现了你原始post中的代码,一切似乎都适合我 – 你在哪里获得了InMemoryDbSet的源代码? 我正在使用NuGet包1.3 ,也许你应该尝试那个版本?