C# 模拟 Database.ExecuteSqlRaw [英] C# Mocking Database.ExecuteSqlRaw
本文介绍了C# 模拟 Database.ExecuteSqlRaw的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试模拟 Database.ExecuteSqlCommand,但它提示我 不支持的表达式 无论如何我可以模拟存储库来模拟 dBContext.Database.ExecuteSqlCommand>
Repository.cs
private readonly Mock_dbContextMock;公共 ShippingBulkRepositoryTest(){_dbContextMock = new Mock(new DbContextOptionsBuilder().Options);_repository = new Repository(_dbContextMock.Object);}公共异步任务 deleteAllRecords(CancellationToken cancellingToken){尝试{dBContext.Database.ExecuteSqlCommand(从批量删除");dBContext.SaveChanges();捕获(异常前){Console.WriteLine(ex);}}
RepositoryTest
[事实]公共异步任务 deleteAllRecords_should_call_GetAllSortedByPlateAsync_onto_service(){//给定var 批量 = _fixture.Build().With(x => x.id, 1).With(x => x.type, "bulk").CreateMany(1);//_dbContextMock.Setup(x => x.Database.ExecuteSqlRaw(It.IsAny()));//什么时候等待 _repository.deleteAllRecords(默认);//然后_dbContextMock.Verify(x => x.SaveChanges(), Times.Once);}
错误
消息:值不能为空.(参数'databaseFacade')
解决方案
最新版本的 EF 核心允许您使用 内存数据库提供程序来运行这种集成测试.
I am trying to mock the Database.ExecuteSqlCommand but it prompted me Unsupported expression Is there anyway that I can mock the repository to mock dBContext.Database.ExecuteSqlCommand
Repository.cs
private readonly Mock<DBContext> _dbContextMock;
public ShippingBulkRepositoryTest()
{
_dbContextMock = new Mock<DBContext>(new DbContextOptionsBuilder<DBContext>().Options);
_repository = new Repository(_dbContextMock.Object);
}
public async Task deleteAllRecords(CancellationToken cancellationToken)
{
try
{
dBContext.Database.ExecuteSqlCommand("DELETE FROM bulk");
dBContext.SaveChanges();
} catch (Exception ex)
{
Console.WriteLine(ex);
}
}
RepositoryTest
[Fact]
public async Task deleteAllRecords_should_call_GetAllSortedByPlateAsync_onto_service()
{
//given
var bulk = _fixture.Build<bulk>()
.With(x => x.id, 1)
.With(x => x.type, "bulk")
.CreateMany(1);
//_dbContextMock.Setup(x => x.Database.ExecuteSqlRaw(It.IsAny<string>()));
//when
await _repository.deleteAllRecords(default);
//then
_dbContextMock.Verify(x => x.SaveChanges(), Times.Once);
}
Error
Message:
Value cannot be null. (Parameter 'databaseFacade')
解决方案
The latest versions of EF core allow you to use the in-memory database provider to run this kind of integration test.
这篇关于C# 模拟 Database.ExecuteSqlRaw的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文