我怎么能模拟FromSql()方法?

时间:2016-11-21 18:07:02

标签: c# unit-testing entity-framework-core moq

我想知道除了构建用于模拟FromSql的包装器之外还有什么方法吗?我知道这个方法是静态的,但是因为他们将AddEntityFrameworkInMemoryDatabase之类的东西添加到实体框架核心,我认为也可能有这样的解决方案,我在我的项目中使用EF Core 1.0.1。

我的最终目标是测试此方法:

public List<Models.ClosestLocation> Handle(ClosestLocationsQuery message)
{
    return _context.ClosestLocations.FromSql(
        "EXEC GetClosestLocations {0}, {1}, {2}, {3}",
        message.LocationQuery.Latitude,
        message.LocationQuery.Longitude,
        message.LocationQuery.MaxRecordsToReturn ?? 10,
        message.LocationQuery.Distance ?? 10
    ).ToList();
}

我想确保我的查询是使用我传入其中的相同对象来处理的,基于实体框架6中的this answer我可以这样做:

[Fact]
public void HandleInvokesGetClosestLocationsWithCorrectData()
{
    var message = new ClosestLocationsQuery
    {
        LocationQuery =
            new LocationQuery {Distance = 1, Latitude = 1.165, Longitude = 1.546, MaxRecordsToReturn = 1}
    };

    var dbSetMock = new Mock<DbSet<Models.ClosestLocation>>();

    dbSetMock.Setup(m => m.FromSql(It.IsAny<string>(), message))
        .Returns(It.IsAny<IQueryable<Models.ClosestLocation>>());

    var contextMock = new Mock<AllReadyContext>();

    contextMock.Setup(c => c.Set<Models.ClosestLocation>()).Returns(dbSetMock.Object);

    var sut = new ClosestLocationsQueryHandler(contextMock.Object);
    var results = sut.Handle(message);

    contextMock.Verify(x => x.ClosestLocations.FromSql(It.IsAny<string>(), It.Is<ClosestLocationsQuery>(y =>
        y.LocationQuery.Distance == message.LocationQuery.Distance &&
        y.LocationQuery.Latitude == message.LocationQuery.Latitude &&
        y.LocationQuery.Longitude == message.LocationQuery.Longitude &&
        y.LocationQuery.MaxRecordsToReturn == message.LocationQuery.MaxRecordsToReturn)));
}

但与EF 6中的SqlQuery<T>不同,EF Core中的FromSql<T>是静态扩展方法,我问这个问题,因为我想我可能会从错误的角度处理这个问题或者那里可能是一个比包装纸更好的选择,我对此有任何想法。

3 个答案:

答案 0 :(得分:4)

我也陷入了同样的境地,菲利普给出了答案,但主要的方法是投掷System.ArgumentNullException

this link开始,我终于能够编写一些单元测试......

这是我的课程:

public class HolidayDataAccess : IHolidayDataAccess
{
    private readonly IHolidayDataContext holDataContext;

    public HolidayDataAccess(IHolidayDataContext holDataContext)
    {
        this.holDataContext = holDataContext;
    }

    public async Task<IEnumerable<HolidayDate>> GetHolidayDates(DateTime startDate, DateTime endDate)
    {
        using (this.holDataContext)
        {
            IList<HolidayDate> dates = await holDataContext.Dates.FromSql($"[dba].[usp_GetHolidayDates] @StartDate = {startDate}, @EndDate = {endDate}").AsNoTracking().ToListAsync();
            return dates;
        }
    }
}

这是测试方法:

[TestMethod]
public async Task GetHolidayDates_Should_Only_Return_The_Dates_Within_Given_Range()
{
    // Arrange.

        SpAsyncEnumerableQueryable<HolidayDate> dates = new SpAsyncEnumerableQueryable<HolidayDate>();
        dates.Add(new HolidayDate() { Date = new DateTime(2018, 05, 01) });
        dates.Add(new HolidayDate() { Date = new DateTime(2018, 07, 01) });
        dates.Add(new HolidayDate() { Date = new DateTime(2018, 04, 01) });
        dates.Add(new HolidayDate() { Date = new DateTime(2019, 03, 01) });
        dates.Add(new HolidayDate() { Date = new DateTime(2019, 02, 15) });


    var options = new DbContextOptionsBuilder<HolidayDataContext>()
        .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
        .Options;

    HolidayDataContext context = new HolidayDataContext(options);

    context.Dates = context.Dates.MockFromSql(dates);

    HolidayDataAccess dataAccess = new HolidayDataAccess(context);

    //Act.
    IEnumerable<HolidayDate> resutlDates = await dataAccess.GetHolidayDates(new DateTime(2018, 01, 01), new DateTime(2018, 05, 31));

    // Assert.

    Assert.AreEqual(resutlDates.Any(d => d.Date != new DateTime(2019, 03, 01)), true);
    Assert.AreEqual(resutlDates.Any(d => d.Date != new DateTime(2019, 02, 15)), true);

    // we do not need to call this becuase we are using a using block for the context...
    //context.Database.EnsureDeleted();
}

要使用UseInMemoryDatabase,您需要从NuGet添加Microsoft.EntityFrameworkCore.InMemory个包 辅助类在这里:

public class SpAsyncEnumerableQueryable<T> : IAsyncEnumerable<T>, IQueryable<T>
{
    private readonly IList<T> listOfSpReocrds;

    public Type ElementType => throw new NotImplementedException();

    public IQueryProvider Provider => new Mock<IQueryProvider>().Object;

    Expression IQueryable.Expression => throw new NotImplementedException();

    public SpAsyncEnumerableQueryable()
    {
        this.listOfSpReocrds = new List<T>();
    }        

    public void Add(T spItem) // this is new method added to allow xxx.Add(new T) style of adding sp records...
    {
        this.listOfSpReocrds.Add(spItem);
    }

    public IEnumerator<T> GetEnumerator()
    {
       return this.listOfSpReocrds.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

    IAsyncEnumerator<T> IAsyncEnumerable<T>.GetEnumerator()
    {
        return listOfSpReocrds.ToAsyncEnumerable().GetEnumerator();
    }
}

...以及包含FromSql方法模拟的Db扩展类..

public static class DbSetExtensions
{
    public static DbSet<T> MockFromSql<T>(this DbSet<T> dbSet, SpAsyncEnumerableQueryable<T> spItems) where T : class
    {
        var queryProviderMock = new Mock<IQueryProvider>();
        queryProviderMock.Setup(p => p.CreateQuery<T>(It.IsAny<MethodCallExpression>()))
            .Returns<MethodCallExpression>(x => spItems);

        var dbSetMock = new Mock<DbSet<T>>();
        dbSetMock.As<IQueryable<T>>()
            .SetupGet(q => q.Provider)
            .Returns(() => queryProviderMock.Object);

        dbSetMock.As<IQueryable<T>>()
            .Setup(q => q.Expression)
            .Returns(Expression.Constant(dbSetMock.Object));
        return dbSetMock.Object;
    }
}

希望这有帮助!

编辑:重构SpAsyncEnumerableQueryable类以使用Add方法。摆脱了采用T数组的参数化构造。已实现IQueryProvider Provider => new Mock<IQueryProvider>().Object;以支持.AsNoTracking()。异步调用ToList。

答案 1 :(得分:3)

如果您查看FromSql<T>中的代码,就可以看到它调用source.Provider.CreateQuery<TEntity>。这就是你必须要模仿的东西。

在你的情况下,我认为你可以用这样的东西来解决这个问题:

var mockProvider = new Mock<IQueryProvider>();
mockProvider.Setup(s => s.CreateQuery(It.IsAny<MethodCallExpression>()))
    .Returns(null as IQueryable);
var mockDbSet = new Mock<DbSet<AllReady.Models.ClosestLocation>>();
mockDbSet.As<IQueryable<AllReady.Models.ClosestLocation>>()
    .Setup(s => s.Provider)
    .Returns(mockProvider.Object);
var t = mockDbSet.Object;
context.ClosestLocations = mockDbSet.Object;

var sut = new ClosestLocationsQueryHandler(context);
var results = sut.Handle(message);

之后不确定如何Verify MethodCallExpression,但我认为这是可能的。或者,可能有一种方法可以检查生成的SQL。

答案 2 :(得分:0)

旧线程旧;但是,如果有人在寻找; 可以对来自sql的调用执行Moq验证,您必须针对查询提供程序进行验证。

INSERT OR IGNORE INTO UserCert (UserName,DocType) SELECT UserName,('Card_FRM','Card_GST','Card_INV','Card_REG','Passport') FROM Users WHERE isVIP=0;

同样的方法也适用于NSub。

方法调用表达式验证可以进行微调以匹配sql和参数,它包含sql(RawSqlString)和参数(IEnumerable)作为常量表达式。

var providerMock = Mock.Get(((IQueryable<TestEntity>) mockedDbContext.Set<TestEntity>()).Provider);
providerMock.Verify(m => m.CreateQuery<TestEntity>(It.IsAny<MethodCallExpression>()), Times.Once);

其中mce是馈给var mceRawSqlString = (RawSqlString) ((ConstantExpression) mce.Arguments[1]).Value; var mceParameters = (object[]) ((ConstantExpression) mce.Arguments[2]).Value 的{​​{1}}。

我在项目EntityFrameworkCore.Testing中做了一些MCE解构,以支持FromSql模拟;我将实际匹配方法与支持方法进行了比较,因为它有点麻烦。

MethodCallExpression