我从来没有真正做过单元测试,而且我偶然发现了我的第一个测试.问题是_repository.Golfers.Count();始终表示DbSet为空.
我的测试很简单,我只是想添加一个新的高尔夫球手
[TestClass] public class GolferUnitTest //: GolferTestBase { public MockGolfEntities _repository; [TestMethod] public void ShouldAddNewGolferToRepository() { _repository = new MockGolfEntities(); _repository.Golfers = new InMemoryDbSet<Golfer>(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<Golfer> 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() }; }
我已经使用实体框架和代码优先建立了一个数据模型.我为IDbSet嘲笑一个派生类,以便测试我的上下文(对于在线的人来说,我完全不记得)
public class InMemoryDbSet<T> : IDbSet<T> where T : class { readonly HashSet<T> _set; readonly IQueryable<T> _queryableSet; public InMemoryDbSet() : this(Enumerable.Empty<T>()) { } public InMemoryDbSet(IEnumerable<T> entities) { _set = new HashSet<T>(); 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并填充了三个假的高尔夫球手,但是当我退出添加功能时,_respoistory.Golfers再次为空.当我添加一个新的高尔夫球手,_set.Add(实体)运行,并且添加了高尔夫球手,但是再次_respoistory.Golfers是空的.我在这里缺少什么?
更新
我很抱歉成为一个白痴,但是我没有在我的MockGolfEntities上下文中实现该集.我没有的原因是我以前尝试,但无法弄清楚如何,继续,忘记了.那么,如何设置一个IDbSet?这是我试过的,但它给我一个Stack Overflow错误.我觉得像一个白痴,但是我无法弄清楚如何写入set函数.
public class MockGolfEntities : DbContext,IContext { public MockGolfEntities() {} public IDbSet<Golfer> Golfers { get { return new InMemoryDbSet<Golfer>(); } set { this.Golfers = this.Set<Golfer>(); } } }