我试图模拟数据库操作.我在模拟sqlParameterCollection时遇到问题.我试图创建将返回DbParameterCollection的虚方法,但后来我失去了sqlParameterCollection给出的所有功能,如AddWithValue等.有没有办法可以模拟sqlParameterCollection?单元测试DAL还有其他方法吗?我正在使用Moq.
代码是这样的:
在DAL:
protected virtual IDbConnection GetConnection(string connectionString) { return new sqlConnection(connectionString); } protected virtual IDbCommand GetCommand(IDbConnection cn) { return cn.CreateCommand(); } protected virtual IDbTransaction GetTransaction(IDbConnection cn) { return cn.BeginTransaction(IsolationLevel.Serializable); } Public Bool InsertInDatabase(DataTable dt) { using (IDbConnection cn = GetConnection(cnstr)) { cn.Open(); using (IDbTransaction tran = GetTransaction(cn)) { IDbCommand cmd = GetCommand(cn); cmd.Transaction = tran; cmd.Connection = cn; cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "sp_InsertInDatabase"; sqlParameterCollection cmdParams = cmd.Parameters as sqlParameterCollection; cmdParams.AddWithValue("@param1",dt); cmd.ExecuteNonQuery(); } } }
在单元测试项目中:
protected override IDbConnection GetConnection(string connectionString) { return Mock.Of<IDbConnection>(); } protected override IDbCommand GetCommand(IDbConnection cn) { return Mock.Of<IDbCommand>(); } protected override IDbTransaction GetTransaction(IDbConnection cn) { return Mock.Of<IDbTransaction>(); } public void TestInsertInDatabase() { base.InsertInDatabase(new DataTable()); }
– 解 –
创建了一个扩展方法来添加带有值的参数.谢谢Marc Gravell指出我的方向.
public static IDbDataParameter AddParameterWithValue(this IDbCommand cmd,string paramName,object paramValue) { var dbParam = cmd.CreateParameter(); if (dbParam != null) { dbParam.ParameterName = paramName; dbParam.Value = paramValue; } return dbParam; }
解决方法
就个人而言,我通过向DbCommand(或IDbCommand)编写AddParameterWithValue扩展方法来解决此问题.它必须在命令上才能访问
CreateParameter
,然后调用.Parameters.Add.
这允许轻松使用任何ADO.NET堆栈,包括日志记录装饰器等抽象.