Moq to Rhino - fake partial repository

心不动则不痛 提交于 2019-12-11 03:09:01

问题


I got this really cool Moq method that fakes out my GetService, looks like this

private Mock<IGetService<TEntity>> FakeGetServiceFactory<TEntity>(List<TEntity> fakeList) where TEntity : class, IPrimaryKey, new()
{
     var mockGet = new Mock<IGetService<TEntity>>();
     mockGet.Setup(mock => mock.GetAll()).Returns(fakeList);
     mockGet.Setup(mock => mock.Get(It.IsAny<int>())).Returns((int i) => fakeList.Find(fake => fake.Id.ToString() == i.ToString()));
     mockGet.Setup(mock => mock.Get(It.IsAny<Expression<Func<TEntity, bool>>>())).Returns((Expression<Func<TEntity, bool>> expression) => fakeList.AsQueryable().Where(expression));

     return mockGet;
}

and to use this...

var fakeList = new List<Something>();
fakeList.Add(new Something { Whatever = "blah" });
//do this a buncha times

_mockGetService = FakeGetServiceFactory(fakeList);
_fakeGetServiceToInject = _mockGetService.Object;

How do I toss this into Rhino.Mock?


回答1:


Something along these lines (sorry, I don't have VS handy, so I can't test it):

private IGetService<TEntity> FakeGetServiceFactory<TEntity>(List<TEntity> fakeList) where TEntity : class, IPrimaryKey, new()
{
     var mockGet = MockRepository.GenerateMock<IGetService<TEntity>>();
     mockGet.Expect(mock => mock.GetAll()).Return(fakeList);
     mockGet.Expect(mock => mock.Get(Arg<int>.Is.Anything)).Do((int i) => fakeList.Find(fake => fake.Id.ToString() == i.ToString()));
     mockGet.Expect(mock => mock.Get(Arg<Expression<Func<TEntity, bool>>>.Is.Anything)).Do((Expression<Func<TEntity, bool>> expression) => fakeList.AsQueryable().Where(expression));

     return mockGet;
}


来源:https://stackoverflow.com/questions/3237757/moq-to-rhino-fake-partial-repository

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