How can i mock data access layer using Rhino mocks I 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 classDataAccess
is calledTHEN
command.ExecuteNonQuery()
should be called:Hope that explains a bit how to use Rhino Mock.
I assume you want to test DbOperation by mocking DataAccess.
Ideally, you may want to even inject
IDbObjectFactory<T>
so that you can test the interaction between DbOperation and the sqlParameterFactory - and hence you could also check thatExecuteNoneQuery
was called with the exact parameters that sqlParameterFactory would return.