如何从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."
答案 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
调用的参数匹配。我把它留给你。