模拟Generic Repository / UnitOfWork

时间:2015-03-01 11:47:08

标签: c# entity-framework unit-testing nunit rhino-mocks

如何从Generic repo和service测试Insert Method? 我有这个通用的回购:

IEnumerable<TEntity> Get(
    Expression<Func<TEntity, bool>> filter = null,
    Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
    string includeProperties = "");

TEntity GetById(object id);

IEnumerable<TEntity> GetAll();

void Insert(TEntity entity);

void Delete(object id);

void Delete(TEntity entityToDelete);

void Update(TEntity entityToUpdate);

这个工作单元:

IGenericRepository<Department> DepartmentRepository { get; }

和这项服务

public void Insert(string depName, List<Post> posts = null)
{
    try
    {
        var department = new Department(depName, posts);
        unitOfWork.DepartmentRepository.Insert(department);
        unitOfWork.Save();
    }
    catch (Exception ex)
    {
        ErrorSignal.FromCurrentContext().Raise(ex);
        return;
    }
}

我希望使用Rhino.Mock

测试此服务方法
 var mocks = new MockRepository();
IUnitOfWork unitOfWork = mocks.Stub<IUnitOfWork>();
Department dep = new Department("test");
var id = Guid.NewGuid().ToString();

unitOfWork.Expect(svc => svc.DepartmentRepository.Insert(dep));
unitOfWork.Expect(svc => svc.Save());

DepartmentService depService = new DepartmentService(unitOfWork);
// Act
mocks.ReplayAll();
depService.Insert(dep.Name);
var result = depService.GetAll();

我总是遇到错误,有人能帮助我吗? 错误:

"IUnitOfWork.get_DepartmentRepository(); Expected #1, Actual #2."

1 个答案:

答案 0 :(得分:2)

应该做的事情很少:

  • 可以通过静态MockRepository.GenerateMock方法创建模拟实例(您使用的存储库实例是旧API)
  • DepartmentRepository属性应该被模拟为Insert将进行呼叫验证
  • mocks.ReplayAll()不需要
  • 不需要致电depService.GetAll() - 在您的测试中,您将数据插入到模拟中,这些模拟不会在任何地方插入任何内容,因此会提取 数据不会产生任何结果

考虑到以上几点,您的测试应该更接近于此:

// Arrange
// 1. Instantiate mocks
var unitOfWork = MockRepository.GenerateMock<IUnitOfWork>();
var repository = MockRepository.GenerateMock<IGenericRepository<Department>>();
// 2. Setup unit of work to return mocked repository
unitOfWork.Stub(uow => uow.DepartmentRepository).Returns(repository);
// 3. Setup expectations - note that we ignore Department argument
repository.Expect(rep => rep.Insert(Arg<Department>.Is.Anything));
unitOfWork.Expect(uow => uow.Save());
var dep = new Department("test");
var depService = new DepartmentService(unitOfWork);

// Act
depService.Insert(dep.Name);

// Assert
repository.VerifyAllExpectations();
unitOfWork.VerifyAllExpectations();

很少有东西可以改进 - 例如,Insert调用的参数匹配。我把它留给你。