Mocking data access Layer Rhino mock

2019-06-12 00:37发布

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);
        }
    }

2条回答
够拽才男人
2楼-- · 2019-06-12 01:23

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.

查看更多
做个烂人
3楼-- · 2019-06-12 01:27

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.

查看更多
登录 后发表回答