使用Moq时,在Dapper方法上获取NotSupportedException

时间:2017-08-15 17:08:02

标签: c# unit-testing moq dapper notsupportedexception

使用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> 方法。 我做错了什么?

2 个答案:

答案 0 :(得分:4)

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

将该功能封装在您控制的抽象背后,并且可以模拟。

答案 1 :(得分:2)

我倾向于使用自己的对象包装外部库,以使测试变得简单,并且语言也很适合。此外,您将这些库中的潜在更改隔离到包装对象。此外,您还可以快速向方法添加缓存等功能。但最重要的是,因为它与这个问题有关,你可以很容易地模仿它。

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...)