Ham*_*lla 6 c# unit-testing moq entity-framework-core
我想知道除了构建一个用于模拟的包装器之外还有什么方法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();
}
Run Code Online (Sandbox Code Playgroud)
我想确保我的查询是使用我传入其中的相同对象来处理的,基于实体框架6中的这个答案,我可以这样做:
[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)));
}
Run Code Online (Sandbox Code Playgroud)
但是与SqlQuery<T>EF 6 不同,EF FromSql<T>Core中的静态扩展方法,我问这个问题,因为我认为我可能从错误的角度处理这个问题,或者可能有一个比包装器更好的选择,我很感激任何想法就此而言.
我也陷入了同样的情况,菲利普(Philippe)给出的回答有所帮助,但主要方法是投掷System.ArgumentNullException。
通过这个链接,我终于能够编写一些单元测试...
这是我的课程正在测试:
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是测试方法:
[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();
}
Run Code Online (Sandbox Code Playgroud)
要使用它,UseInMemoryDatabase您需要Microsoft.EntityFrameworkCore.InMemory从NuGet添加软件包
。帮助器类在这里:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
...以及包含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;
}
}
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助!
编辑:重构SpAsyncEnumerableQueryable类以具有Add方法。摆脱了采用T数组的参数化构造。实现IQueryProvider Provider => new Mock<IQueryProvider>().Object;以支持.AsNoTracking()。异步调用ToList。
| 归档时间: |
|
| 查看次数: |
3328 次 |
| 最近记录: |