How do you mock adding items to a repository or DbContext using moq?

前端 未结 5 1128
猫巷女王i
猫巷女王i 2021-01-23 17:00

The examples I\'ve seen for using moq for a repository only show how to mock things being returned. I have a somewhat strange requirement: when a query is executed, if a conditi

5条回答
  •  粉色の甜心
    2021-01-23 17:27

    Try to use fake in memory repository instead of moq, for example universal generic repository for all entities:

    public interface IInMemoryRepository where T : class
    {
        IQueryable GetAll();
        void Create(T item);
        void Update(T item);
        T GetItem(Expression> expression);
        void Delete(T item);
    }
    
    public class InMemoryRepository : IInMemoryRepository where T : class
    {
        private int _incrementer = 0;
        public Dictionary List = new Dictionary();
    
        public IQueryable GetAll()
        {
            return List.Select(x => x.Value).AsQueryable();
        }
    
        public void Create(T item)
        {
            _incrementer++;
            item.GetType().GetProperties().First(p => p.Name == "Id").SetValue(item, _incrementer, null);
            List.Add(_incrementer, item);
        }
    
        public void Update(T item)
        {
            var key = (int)item.GetType().GetProperties().First(p => p.Name == "Id").GetValue(item, null);
            List[key] = item;
        }
    
        public T GetItem(Expression> expression)
        {
            return List.Select(x => x.Value).SingleOrDefault(expression.Compile());
        }
    
        public void Delete(T item)
        {
            var key = (int)item.GetType().GetProperties().First(p => p.Name == "Id").GetValue(item, null);
            List.Remove(key);
        }
    }
    

提交回复
热议问题