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 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.
I assume you want to test DbOperation by mocking DataAccess.
public void TestInsert()
{
var dataAccess = MockRepository.GenerateMock<IDataAccess>();
var dbOperation = new DbOperation<string>(dataAccess);
var sqlConnection = new SqlConnection();
dbOperation.Insert("blah", sqlConnection, "MySP");
dataAccess.AssertWasCalled(a => a.ExecuteNoneQuery(
Arg.Is(sqlConnection),
Arg.Is("MySP"),
Arg<IEnumerable<SqlParameter>>.Is.Anything));
}
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 that ExecuteNoneQuery
was called with the exact parameters that sqlParameterFactory would return.