Mocking data access Layer Rhino mock

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-08 11:59:58

问题


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

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/16024506/mocking-data-access-layer-rhino-mock

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!