需要帮助模拟接口

Need help mocking interface

我有以下方法可以测试:

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)});
        }

但是它没有编译,模拟方法的 return 类型有错误。它说缺少一个分号,但如果我添加它,它又坏了,我很难修复它。

好的,我找到了解决方案,我采用了错误的方法。我需要执行函数参数 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);
        }