Hi,
I want to test some database logic. I've written a test which calls a class which simply logs the current date:
[Fact] public async Task LogCurrentDate_DbIsEmptyTest() { var emptyData = new List<DateTimeLog> { }; var mockDateTimeSet = new Mock<DbSet<DateTimeLog>>(); mockDateTimeSet.As<IQueryable<DateTimeLog>>().Setup(m => m.Provider).Returns(emptyData.AsQueryable().Provider); mockDateTimeSet.As<IQueryable<DateTimeLog>>().Setup(m => m.Expression).Returns(emptyData.AsQueryable().Expression); mockDateTimeSet.As<IQueryable<DateTimeLog>>().Setup(m => m.ElementType).Returns(emptyData.AsQueryable().ElementType); mockDateTimeSet.As<IQueryable<DateTimeLog>>().Setup(m => m.GetEnumerator()).Returns(emptyData.GetEnumerator()); mockDateTimeSet.As<IListSource>().Setup(m => m.GetList()).Returns((List<DateTimeLog>)emptyData); var mockDbContext = new Mock<QlcContext>(); mockDbContext.Setup(repo => repo.DateTimeLog).Returns(mockDateTimeSet.Object); DateTimeLogger dateTimeLogger = new DateTimeLogger(mockDbContext.Object); await dateTimeLogger.LogCurrentDate(); var entries = mockDateTimeSet.Object.ToList(); // List is still empty! Assert.Equal(DateTime.UtcNow.Date, entries[0].DateTimeActivityLog); // Test fails! }
I'm providing a mockup and I expect, that the emptyData mock gets filled by thedateTimeLogger instance, but when I test the result at the end, the list is still empty.
My DateTimeLogger class uses code like:
await _dbContext.DateTimeLog.AddAsync(newLogEntry); await _dbContext.SaveChangesAsync();
Where's the problem?
Thanks in advance!
Stefano