我创建了一个方法来检查db中是否有存储过程。
public class StoredProcedure : IStoredProcedure
{
private readonly IDbContextProvider<MyDbContext> _dbContextProvider;
public StoredProcedure(IDbContextProvider<MyDbContext> dbContextProvider)
{
_dbContextProvider = dbContextProvider;
}
public bool ExistsStoredProcedure(string procedureName)
{
var query = string.Format(
"SELECT COUNT(*) FROM [sys].[objects] WHERE [type_desc] = 'SQL_STORED_PROCEDURE' AND [name] = '{0}';",
procedureName);
var request = _dbContextProvider.DbContext.Database.SqlQuery<int>(query).Single();
return request > 0 ? true : throw new UserFriendlyException(
$"Хранимая процедура {procedureName} не найдена в БД {_dbContextProvider.DbContext.Database.Connection.Database}");
}
}
此外,我想为他编写一个单元测试。
public class StoredProcedureTests
{
private readonly IStoredProcedure _storedProcedure;
private readonly Mock<IDbContextProvider<MyDbContext>> _mockDbProvider;
public StoredProcedureTests()
{
_mockDbProvider = new Mock<IDbContextProvider<MyDbContext>>();
_storedProcedure = new StoredProcedure(_mockDbProvider.Object);
}
[Fact]
public void CheckValueIfStoredProcedureExist()
{
const int count = 1;
var rawMock = new Mock<DbRawSqlQuery<int>>();
rawMock.Setup(i => i.Single()).Returns(count);
_mockDbProvider.Setup(i => i.DbContext.Database.SqlQuery<int>(It.IsAny<string>())).Returns(rawMock.Object);
var result = _storedProcedure.ExistsStoredProcedure(string.Empty);
Assert.True(result);
}
}
但是,当我尝试rawMock.Setup时出现错误
try
{
rawMock.Setup(i => i.Single()).Returns(count);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
throw;
}
扩展方法上的设置无效:i => i.Single()
如何正确编写此存根?
UPD ,我尝试像约翰尼建议的那样
try
{
IEnumerable<int> list = new List<int> {1};
var mq = new Mock<DbRawSqlQuery<int>>();
mq.Setup(i => i.GetEnumerator()).Returns(list.GetEnumerator);
_mockDbProvider.Setup(i => i.DbContext.Database.SqlQuery<int>(It.IsAny<string>())).Returns(mq.Object);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
throw;
}
我有一个新错误
在非虚拟成员(在VB中可重写)上的无效设置:i => i.DbContext.Database.SqlQuery(It.IsAny(),new [] {})