本文介绍了惩戒数据访问层模拟犀牛的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何使用犀牛制品
我有以下类模拟数据访问层:
公共接口IDataAccess
{
INT ExecuteNoneQuery(SqlConnection的连接字符串storedProcedureName,
IEnumerable的<&SqlParameter的GT; sqlParameters);
}
公共类数据访问:IDataAccess
{
公众诠释ExecuteNoneQuery(SqlConnection的连接字符串storedProcedureName,
的IEnumerable<的SqlParameter> sqlParameters )
{
使用(的SqlCommand命令= connection.CreateCommand())
{
//做一些东西
返回command.ExecuteNonQuery();
}
}
}
公共类DbOperation< T>
{
私人IDataAccess _access;
公共DbOperation(IDataAccess访问)
{
_access =接入;
}
公众诠释插入(T项目,SqlConnection的连接字符串spName)
{
IDbObjectFactory< T> parametersFactory =新SqlParameterFactory< T>();
VAR参数=(IList的<&SqlParameter的GT;)parametersFactory.GetDbObject(项目);
返回_access.ExecuteNoneQuery(连接,spName,参数);
}
}
解决方案
下面是一些解释一个例子:
要测试的情况:结果
当方式 ExecuteNoneQuery
类数据访问
被称为结果
,则 command.ExecuteNonQuery()
应该叫:
// 1.创建`SqlCommand`模拟:
VAR命令= MockRepository.GenerateMock<&的SqlCommand GT;();
// 2.创建`SqlConnection`存根:
VAR连接= MockRepository.GenerateStub< SqlConnection的>();
// 3.设置connection.CreateCommand()返回嘲笑命令:
连接
.Stub(C => c.CreateCommand())
。返程(命令);
// 4.是否测试动作:
VAR数据访问=新的DataAccess();
dataAccess.ExecuteNoneQuery(连接,NULL,NULL);
//断言command.ExecuteNonQuery()被调用:
command.AssertWasCalled(C => c.ExecuteNonQuery());
希望,解释了一下如何使用犀牛模拟。
How can i mock data access layer using Rhino mocksI have the following classes:
public interface IDataAccess
{
int ExecuteNoneQuery(SqlConnection connection, string storedProcedureName,
IEnumerable<SqlParameter> sqlParameters);
}
public class DataAccess : IDataAccess
{
public int ExecuteNoneQuery(SqlConnection connection, string storedProcedureName,
IEnumerable<SqlParameter> sqlParameters)
{
using (SqlCommand command = connection.CreateCommand())
{
// do some stuff
return command.ExecuteNonQuery();
}
}
}
public class DbOperation<T>
{
private IDataAccess _access;
public DbOperation(IDataAccess access)
{
_access = access;
}
public int Insert(T item, SqlConnection connection,string spName)
{
IDbObjectFactory<T> parametersFactory = new SqlParameterFactory<T>();
var parameters = (IList<SqlParameter>)parametersFactory.GetDbObject(item);
return _access.ExecuteNoneQuery(connection, spName, parameters);
}
}
解决方案
Here is an example with some explanations:
To test the case:
WHEN method ExecuteNoneQuery
of class DataAccess
is called
THEN command.ExecuteNonQuery()
should be called:
// 1. Create `SqlCommand` Mock:
var command = MockRepository.GenerateMock<SqlCommand>();
// 2. Create `SqlConnection` Stub:
var connection = MockRepository.GenerateStub<SqlConnection>();
// 3. Setup connection.CreateCommand() to return mocked command:
connection
.Stub(c => c.CreateCommand())
.Return(command);
// 4. Do test action:
var dataAccess = new DataAccess();
dataAccess.ExecuteNoneQuery(connection, null, null);
// Assert command.ExecuteNonQuery() has been called:
command.AssertWasCalled(c => c.ExecuteNonQuery());
Hope that explains a bit how to use Rhino Mock.
这篇关于惩戒数据访问层模拟犀牛的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!