I was wondering is there any way other than building a wrapper for mocking the FromSql
? I know this method is static, but since they added things like AddEntityFrameworkInMemoryDatabase
to entity framework core, I thought there might be a solution for this too, I use EF Core 1.0.1 in my project.
My end goal is to test this method:
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();
}
I want to ensure that my query is handled with the same object that I passed into it, based on this answer in entity framework 6 I could do something like this:
[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)));
}
But unlike SqlQuery<T>
in EF 6, the FromSql<T>
in EF Core is static extension method, I'm asking this question because I think I might approach this problem from the wrong angle or there might be a better alternative than a wrapper, I'd appreciate any thought on this.