使用 Moq
时我在下面收到此异常:
System.NotSupportedException: 'Expression references a method that does not belong to the mocked object: c => c.Query<MyClass>(It.IsAny<String>(), It.IsAny<Object>(), It.IsAny<IDbTransaction>(), It.IsAny<Boolean>(), It.IsAny<Nullable`1>(), (Nullable`1)It.IsAny<CommandType>())'
我的类(class):
public class MyClass
{
public int Id {get; set;}
public string Name {get; set;}
}
我实际的 BI 类(class)。我正在使用 Dapper
对于这个类
using Dapper;
//**
//**
//**
using (var con = _readRepository.CreateConnection())
{
var query = "Select * FROM myTable"
return con.Query<MyClass>(query, new { Skip = 0, Take = 10}, null, true, null, null);
}
我的单元测试:
var conMock = new Mock<IDbConnection>();
IEnumerable<MyClass> listModels = new List<MyClass>().AsEnumerable();
//The exception occurrs right here
conMock.Setup(c => c.Query<MyClass>(
It.IsAny<string>(),
It.IsAny<object>(),
It.IsAny<IDbTransaction>(),
It.IsAny<bool>(),
It.IsAny<int?>(),
It.IsAny<CommandType>()
))
.Returns(() => listModels);
//System.NotSupportedException: 'Expression references a method that does not belong to the mocked object: c => c.Query<MyClass>(It.IsAny<String>(), It.IsAny<Object>(), It.IsAny<IDbTransaction>(), It.IsAny<Boolean>(), It.IsAny<Nullable`1>(), (Nullable`1)It.IsAny<CommandType>())'
我只是想做的是模拟 Query<MyClass>
方法。
我做错了什么?
最佳答案
Query<T>
是一种扩展方法。
public static IEnumerable<T> Query<T>(
this IDbConnection cnn,
string sql,
object param = null,
SqlTransaction transaction = null,
bool buffered = true
)
但是 Moq 不能模拟扩展方法。因此,要么模拟该扩展方法内部完成的工作,这将涉及必须去检查 Dapper source code .
或
将该功能封装在您控制并可以模拟的抽象背后。
关于c# - 使用 Moq 时在 Dapper 方法上获取 NotSupportedException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45697883/