c# - 使用 Moq 时在 Dapper 方法上获取 NotSupportedException

标签 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>())'

我的类(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/

相关文章:

c# - WPF 椭圆剪裁

c# - 从 Json 字符串中提取数据

windows - 有没有办法 Hook 或拦截 CoGetClassObject 和/或 CoCreateInstance 调用?

asp.net-mvc - ASP.NET MVC 中的模拟 Controller.Url.Action(string, string, object, string)

c# - 如何先写单元测试后写代码?

c# - 如何将字符串变量作为container.dataitem中的列名传递

c# - WPF应用程序-调用事件操作时不会触发监听方法

unit-testing - 失败的测试是否应该使持续构建失败?

c# - 更改生成的单元测试文件的目录

unit-testing - MOQ - 如何模拟需要转换为另一个接口(interface)的接口(interface)?