Last post Mar 01, 2018 02:21 AM by Edward Z
Feb 26, 2018 01:56 PM|StefanoD86|LINK
I want to test some database logic. I've written a test which calls a class which simply logs the current date:
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);
var entries = mockDateTimeSet.Object.ToList(); // List is still empty!
Assert.Equal(DateTime.UtcNow.Date, entries.DateTimeActivityLog); // Test fails!
I'm providing a mockup and I expect, that the emptyData mock gets filled by the
dateTimeLogger instance, but when I test the result at the end, the list is still empty.
My DateTimeLogger class uses code like:
Where's the problem?
Thanks in advance!
Feb 26, 2018 04:32 PM|bruce (sqlwork.com)|LINK
why should it have any entries? you defined it as an empty list.
in mocked objects, you define the return data from a mocked method calls. if you want ToList() to return something, then define it in the setup stage to return something.
also it looks like you are just unit testing your mock code, which makes no sense. in general you should avoid testing database code.
Feb 26, 2018 05:51 PM|StefanoD86|LINK
Actually I want to test if my class has inserted the right entry in the database. I can't do this by defining what ToList() shall return.
Thanks in advance.
Feb 27, 2018 09:20 AM|Edward Z|LINK
>> I want to test if my class has inserted the right entry in the database
For testing database operation, I would suggest you try test with InMemory features.
# Testing with InMemory
Feb 27, 2018 05:36 PM|StefanoD86|LINK
Thx. I'll will give it tomorrow a try! :)
Mar 01, 2018 02:21 AM|Edward Z|LINK
You could try to download the demo project for a try.
If you have any update about your issue, please feel free to let us know.