简体   繁体   English

Mocking 数据库集<t> EF Core 5 中的 .FromSqlRaw</t>

[英]Mocking DbSet<T>.FromSqlRaw in EF Core 5

On of the repository methods happens to use FromSqlRaw to fetch the data from SQL Server via a stored procedure.一个存储库方法恰好使用FromSqlRaw通过存储过程从 SQL 服务器获取数据。

I am trying to write unit test around it but no luck so far.我正在尝试围绕它编写单元测试,但到目前为止还没有运气。

This is a sample snippet of how far I got这是我走了多远的示例片段

var fixture = new Fixture();
var context = new Mock<IMyDbContext>();
var dbSet = new Mock<DbSet<MyEntity>>();
            
var data = fixture.Build<MyEntity>().CreateMany().AsQueryable();
dbSet.As<IQueryable<MyEntity>>().Setup(m => m.Provider).Returns(data.Provider);
dbSet.As<IQueryable<MyEntity>>().Setup(m => m.Expression).Returns(data.Expression);
dbSet.As<IQueryable<MyEntity>>().Setup(m => m.ElementType).Returns(data.ElementType);
dbSet.As<IQueryable<MyEntity>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator());
context.Setup(c => c.Set<MyEntity>()).Returns(dbSet.Object);

var repository = new MyRepository(context.Object);
 
var result = await repository.GetData();

Bit I got stuck with the following exception位我陷入了以下异常

System.InvalidCastException: Unable to cast object of type 'System.Linq.Expressions.ConstantExpression' to type 'Microsoft.EntityFrameworkCore.Query.QueryRootExpression' System.InvalidCastException:无法将“System.Linq.Expressions.ConstantExpression”类型的 object 转换为“Microsoft.EntityFrameworkCore.Query.QueryRootExpression”类型

The project uses EF Core 5.该项目使用 EF Core 5。

Any idea how to solve this cast exception?知道如何解决这个强制转换异常吗?

Don't mock IQueryable--you're just asking for a world of pain.不要嘲笑 IQueryable——你只是在寻求一个痛苦的世界。 Use a mock repository (possibly backed by an in-memory DbContext) to unit test consuming classes.使用模拟存储库(可能由内存中的 DbContext 支持)对消费类进行单元测试。 Add some integration tests to verify your real repository implementation.添加一些集成测试以验证您的真实存储库实现。

See Testing code that uses EF Core in the docs for more details.有关更多详细信息,请参阅文档中使用 EF Core 的测试代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM