lundi 21 décembre 2015

Mock FirstOrDefault returns NullReferenceException

I would like to understand why my mock dbset is throwing a NullReferenceException when I call dbContext.Object.Locations.FirstOrDefault(x => x.Id == id);

I have setup my mock dbset as detailed below:

 public Mock<DbSet<T>> GetMockDbSet<T>(string path) where T : class
                {
                    var data = GetObjectList<T>(path).AsQueryable();

                    var mockSet = new Mock<DbSet<T>>();
                    mockSet.As<IQueryable<T>>().Setup(m => m.Provider).Returns(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;
                }

 private Mock<DbContext> LoadMockDataBase(ref Dictionary<string, object> mockDictionary)
        {
            var mockSetLocations = GetMockDbSet<Repository.Location>(@"Files/ObjectJson/Locations.json");
dbContext.Setup(l => l.Locations).Returns(mockSetLocations.Object);
        dbContext.Setup(x => x.Locations.AsNoTracking()).Returns(mockSetLocations.Object);
return dbContext;
        }

I understand that if I remove AsNoTracking() this fixes the issue however I do not want to limit the application on not using AsNoTracking simply for passing tests when the logic is correct.

Aucun commentaire:

Enregistrer un commentaire