[英]Getting NotSupportedException on Dapper method when using Moq
使用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>())'
我的课:
public class MyClass
{
public int Id {get; set;}
public string Name {get; set;}
}
我实际的BI课。 我正在为这个课程使用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源代码 。
要么
将该功能封装在您可以控制并可以模拟的抽象后面。
我倾向于将外部库与自己的对象包装在一起,以使测试变得容易和易于使用。 此外,您可以将这些库中的潜在更改隔离到包装对象中。 另外,您可以快速将诸如缓存之类的功能添加到您的方法中。 但最重要的是,因为它与此问题相关,所以您可以轻松地模拟它。
public interface IDatabase{
IDbConnection GetConnection();
IEnumerable<T> Query<T>(whatever you want here...exactly Dapper's parameters if necessary);
}
public class Database : IDatabase{
//implement GetConnection() however you like...open it too!
public IEnumerable<T> Query<T>(...parameters...){
IEnumerable<T> query = null;
using(conn = this.GetConnection()){
query = conn.Query<T>()//dapper's implementation
}
return query;
}
}
现在,您可以使用总控制来模拟IDatabase。
var mockDb = new Mock<IDatabase>();
mockDb.Setup(s=>s.Query(It.IsAny<>...whatever params...).Returns(...whatever you want to return...)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.