我有以下测试方法:
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();
});
}
因此,我需要为此模拟接口IQueryableDataFacade
。我试过了:
[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)});
}
但是它没有编译,在模拟方法的返回类型上有错误。它说少了一个分号,但如果我添加它,它又坏了,我很难修复它。
好吧,我找到了解决方案,我遵循了错误的方法。我需要执行函数参数p,将其作为参数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);
}