我正在尝试测试使用QueryAsync()的存储库方法,并且该方法在事务下。所以我在嘲笑IDbConnection以及IDbTransaction。但是当我运行测试用例时,它会给出错误
“无法将类型为'Castle.Proxies.IDbTransactionProxy'的对象转换为 键入“ System.Data.Common.DbTransaction””
using System;
using Dapper;
using Moq;
using Moq.Dapper;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Collections.Generic;
public class Program
{
public class ComplexType
{
public string StringProperty { get; set; }
public int IntegerProperty { get; set; }
}
private static void TestMoqDapperExecuteAsyncIDbConnectionWithoutTransaction()
{
var connection = new Mock<IDbConnection>();
connection.SetupDapperAsync(c => c.QueryAsync<int>(It.IsAny<string>(), It.IsAny<object>(), It.IsAny<IDbTransaction>(), It.IsAny<int>(), It.IsAny<CommandType>()))
.ReturnsAsync(new List<int>
{
5
});
var result = connection.Object
.QueryAsync<int>("")
.GetAwaiter()
.GetResult();
Console.WriteLine(string.Format(" Test without transaction {0}", result.Count() != 0 ? "PASSED" : "FAILED"));
}
private static void TestMoqDapperExecuteAsyncIDbConnectionWithTransaction()
{
var connection = new Mock<IDbConnection>();
var tran= new Mock<IDbTransaction>();
connection.SetupDapperAsync(c => c.QueryAsync<int>(It.IsAny<string>(), It.IsAny<object>(), It.IsAny<IDbTransaction>(), It.IsAny<int>(), It.IsAny<CommandType>()))
.ReturnsAsync(new List<int>
{
5
});
var result = connection.Object
.QueryAsync<int>("",null,tran.Object)
.GetAwaiter()
.GetResult();
Console.WriteLine(string.Format("Test with transaction {0}", result.Count() != 0 ? "PASSED" : "FAILED"));
}
public static void Main()
{
TestMoqDapperExecuteAsyncIDbConnectionWithoutTransaction();
TestMoqDapperExecuteAsyncIDbConnectionWithTransaction();
}
}
您也可以在小提琴上运行它,以重现相同的问题https://dotnetfiddle.net/40lMbh
答案 0 :(得分:3)
根据异常消息,看来QueryAsync
扩展方法使用了DbTransaction
因此请改用摘要DbTransaction
,它将通过。
TestMoqDapperExecuteAsyncIDbConnectionWithTransaction()
//...
var tran = new Mock<DbTransaction>(); //<--Note abstract class instead of interface
//...
在提供的小提琴上对其进行了测试,并且可以正常工作。