本文介绍了Moq to Rhino-伪造的部分存储库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我得到了一个非常酷的Moq方法,该方法伪造了我的GetService,看起来像这样
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;
}
并使用它...
var fakeList = new List<Something>();
fakeList.Add(new Something { Whatever = "blah" });
//do this a buncha times
_mockGetService = FakeGetServiceFactory(fakeList);
_fakeGetServiceToInject = _mockGetService.Object;
如何将其扔进Rhino.Mock?
How do I toss this into Rhino.Mock?
推荐答案
遵循这些原则(对不起,我没有VS的方便,所以我无法对其进行测试):
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;
}
这篇关于Moq to Rhino-伪造的部分存储库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!