Reputation: 13960
I have the following method to test:
public static DateTime? GetLastSourceUpdateDate(this IQueryableDataFacade facade, long idDevice, long idMeasureType)
{
return facade.ExecuteExpression<SynchonizerLastUpdate, DateTime?>(logs =>
{
return logs.Where(log => log.IdDeviceMeasureType == idMeasureType && log.Device.Id == idDevice).Select(r => r.LastUpdateDate).FirstOrDefault();
});
}
So, I need to mock the interface IQueryableDataFacade
for this. I have tried:
[Fact]
public void ItReturnsNullWhenNoValueIsPresentForThatEntity()
{
List<SynchonizerLastUpdate> datasource = new List<SynchonizerLastUpdate>() {
new SynchonizerLastUpdate() { Id = 1, Device = new Device() { Id = 1}, IdDeviceMeasureType = 1, LastUpdateDate = new DateTime(2020, 1, 1) },
new SynchonizerLastUpdate() { Id = 1, Device = new Device() { Id = 1}, IdDeviceMeasureType = 1, LastUpdateDate = new DateTime(2020, 1, 1) },
new SynchonizerLastUpdate() { Id = 1, Device = new Device() { Id = 1}, IdDeviceMeasureType = 1, LastUpdateDate = new DateTime(2020, 1, 1) }};
var facadeService = new Mock<IQueryableDataFacade>();
facadeService.Setup(m => m.ExecuteExpression<SynchonizerLastUpdate, DateTime?>(It.IsAny<Func<IQueryable<SynchonizerLastUpdate>, DateTime?>>())).Returns((p) => { datasource.Select(p)});
}
But it's not compiling, there's an error on the return type of the mocked method. It says a semicolon is missing, but if I add it, it brokes again, and I'm having troubles to fix it.
Upvotes: 0
Views: 259
Reputation: 13960
Ok, I found the solution, I was following a wrong approach. I need to execute the function parameter p, giving it as parameter the IQueryable
[Fact]
public void ItReturnsRightDateFromDataSource()
{
List<SynchonizerLastUpdate> datasource = new List<SynchonizerLastUpdate>() {
new SynchonizerLastUpdate() { Id = 1, Device = new Device() { Id = 1}, IdDeviceMeasureType = 1, LastUpdateDate = new DateTime(2020, 1, 1) },
new SynchonizerLastUpdate() { Id = 1, Device = new Device() { Id = 2}, IdDeviceMeasureType = 2, LastUpdateDate = new DateTime(2020, 1, 2) },
new SynchonizerLastUpdate() { Id = 1, Device = new Device() { Id = 3}, IdDeviceMeasureType = 3, LastUpdateDate = new DateTime(2020, 1, 3) }};
var facadeService = new Mock<IQueryableDataFacade>();
facadeService.Setup(m => m.ExecuteExpression(It.IsAny<Func<IQueryable<SynchonizerLastUpdate>, DateTime?>>())).Returns((Func<IQueryable<SynchonizerLastUpdate>, DateTime?> p) =>
{
IQueryable<SynchonizerLastUpdate> queryable = datasource.AsQueryable();
return p(queryable);
});
var result = facadeService.Object.GetLastSourceUpdateDate(2, 2);
Assert.Equal(new DateTime(2020, 1, 2), result);
}
Upvotes: 1